100% found this document useful (1 vote)
747 views

Collections of Java Question and Answers

The document contains code examples and explanations of different ways to check if a number is prime in Java using recursion and iteration. It includes programs to check if a single number is prime, find all prime numbers between two given numbers, and check for primality using recursion and a flag variable. The examples demonstrate the core logic and steps to determine primality, such as checking for factors and remainders, as well as the overall structure and usage of methods to solve this problem in Java.

Uploaded by

Yonas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
747 views

Collections of Java Question and Answers

The document contains code examples and explanations of different ways to check if a number is prime in Java using recursion and iteration. It includes programs to check if a single number is prime, find all prime numbers between two given numbers, and check for primality using recursion and a flag variable. The examples demonstrate the core logic and steps to determine primality, such as checking for factors and remainders, as well as the overall structure and usage of methods to solve this problem in Java.

Uploaded by

Yonas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 397

public class nextPerfectSquare{

public static void main(String[] args){


int result = nextPerfectSquare(6);
System.out.println(result);
result = nextPerfectSquare(36);
System.out.println(result);
result = nextPerfectSquare(0);
System.out.println(result);
result = nextPerfectSquare(-5);
System.out.println(result);
}

static int nextPerfectSquare(int n){


int nextPerfectSquare = 0;
if(n >= 0){
double sqrtResult = Math.sqrt(n);
int baseNumber = (int)sqrtResult;
int nextNumber = baseNumber + 1;
nextPerfectSquare = (int)Math.pow(nextNumber, 2);
}
return nextPerfectSquare;
}
}
public class nUpCount{
public static void main(String[] args){
int result = nUpCount(new int[]{2, 3, 1, -6, 8, -3, -1, 2}, 5);
System.out.println(result);
result = nUpCount(new int[]{6, 3, 1}, 6);
System.out.println(result);
result = nUpCount(new int[]{1, 2, -1, 5, 3, 2, -3}, 20);
System.out.println(result);
}

static int nUpCount(int[] a, int n){


int nUpCount = 0;
int partialSum = 0;
int previousPartialSum = 0;
for(int i=0; i<a.length; i++){
previousPartialSum = partialSum;
partialSum += a[i];
if(previousPartialSum <= n && partialSum > n){
nUpCount++;
}
}
return nUpCount;
}
}
There are three questions on the exam. You have
two hours to finish. Please do your own work.
1. Write a function named
primeCount with signature int
primeCount(int start, int end);

The function returns the number of primes between start and end inclusive. Recall
that a prime is a positive integer greater than 1 whose only integer factors are 1
and itself.

Examples
If start and end retur reason
is is n
10 30 6 The primes between 10 and 30 inclusive are 11, 13, 17,
19, 23 and 29
11 29 6 The primes between 11 and 29 inclusive are 11, 13, 17,
19, 23 and 29
20 22 0 20, 21, and 22 are all non-prime
1 1 0 By definition, 1 is not a prime number
5 5 1 5 is a prime number
6 2 0 start must be less than or equal to end
-10 6 3 primes are greater than 1 and 2, 3, 5 are prime

public class primeCount{


public static void main(String[] args){
int result = primeCount(10, 30);
System.out.println(result);
result = primeCount(11, 29);
System.out.println(result);
result = primeCount(20, 22);
System.out.println(result);
result = primeCount(1, 1);
System.out.println(result);
result = primeCount(5, 5);
System.out.println(result);
result = primeCount(6, 2);
System.out.println(result);
result = primeCount(-10, 6);
System.out.println(result);
}

static int primeCount(int start, int end){


int primeCount = 0;
for(int number = start; number <= end; number++){
if(number > 1){
boolean isPrime = true;
for(int divider = 2; divider * 2 <= number;
divider++){
if(number % divider == 0){
isPrime = false;
break;
}
}
if(isPrime){
primeCount++;
}
}
}
return primeCount;
}
}

Prime Number program in


Java
A prime number is a natural number greater than 1 which are divisible by only 1 and itself. For example
2, 3, 5, 7, 11… are prime numbers because they can neither be divided nor is a result of the
multiplication. Programs on Prime numbers are one of the most frequently asked Java interview
questions for freshers. In this post, I have collected some of the important prime number programs in
Java.

• Program to check whether the given number is prime or not


• Program to find out all prime numbers between two given numbers
• Program to check whether the given number is prime or not using recursion
• Program to check if the number is prime or not using a flag variable
• Program to print prime numbers between 1 to 100

Program to check whether the given number is prime or not?

In this java program, I will take a number variable and check whether the number is prime or not.

• The isPrime(int n) method is used to check whether the parameter passed to it is a prime number
or not. If the parameter passed is prime, then it returns True otherwise it returns False.
• If the number is less than 1, if(inputNumber<= 1) it returns false.
• If the number is not less than or equal to 1, performs division operation.
• If the remainder is zero, it returns false, meaning it is not a prime number.
• If it is a non-zero number, it returns true, resulting in a prime number.

package prime;
import java.util.Scanner;

public class PrimeNumberProgram


{
static boolean checkForPrime(int inputNumber)
{
boolean isItPrime = true;
if(inputNumber <= 1)
{
isItPrime = false;
return isItPrime;
}
else
{
for (int i = 2; i<= inputNumber/2; i++)
{
if ((inputNumber % i) == 0)
{
isItPrime = false;
break;
}
}

return isItPrime;
}
}

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number :");
int inputNumber = sc.nextInt();
boolean isItPrime = checkForPrime(inputNumber);

if (isItPrime)
{
System.out.println(inputNumber+" is a prime number.");
}
else
{
System.out.println(inputNumber+" is not a prime
number.");
}

sc.close();
}
}

Note: 0 and 1 are not prime numbers.

The output of this program is:

Let us move to the next program to check prime number program in Java.

Program to find out all prime number between two given numbers
To find the prime number between two natural numbers,

• Check if the number is a natural number.


• Use the IsPrime method to check if the number is prime or not.
• Specify the start number and also the end number.
• For loop to print the prime number.
• You can do that for a series of numbers just specify the range(start and end).

import java.util.Scanner;

public class PrimeNumberProgram


{
static boolean checkForPrime(int inputNumber)
{
boolean isItPrime = true;
if(inputNumber <= 1)
{
isItPrime = false;
return isItPrime;
}
else
{
for (int i = 2; i= inputNumber/2; i++){
if ((inputNumber % i) == 0){
IsItPrime = false;
break;
}
}
return isItPrime;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the start value :");
int start = sc.nextInt();
System.out.println("Enter the end value :");
int end = sc.nextInt();
System.out.println("Prime numbers between "+start+" and "+end+" : ");
for (int i = start; i <= end; i++)
{
if(checkForPrime(i))
{
System.out.println(i);
}
}
sc.close();
}
}

Output:

Program to check whether the number is prime or not using


recursion
• In this case, let’s use recursion to print the prime numbers.
• The Scanner class is a class which is present inside the java.util package, that allows the user to
read values of various types.
• First check if the number is a natural number using if condition, if (n <= 1), return false and print
that the number is not a prime number.
• Check for another condition, that is division, check if the remainder is 0 or not. If the remainder
is 0, then it is not a prime number.

import java.util.Scanner;
public class PrimeUsingRecursion
{
public static void main(String[] args)
{
int n, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter any number:");
n = s.nextInt();
x = isPrime(n);
if(x == 1)
{
System.out.println(n+" is prime number");
}
else
{
System.out.println(n+" is not prime number");
}
}
int isPrime(int y, int i)
{

if(y > i)
{
if(y % i != 0)
{
return(isPrime(y, ++i));
}
else
{
return 0;
}
}
return 1;
}
}

Program to check if the number is prime or not using a flag


variable
• This program helps to print the prime numbers using a flag variable.
• The flag variable is used as a signal in programming to let the user/program know that a certain condition
has met.
• Create a static method checkPrime(int n) and add the conditions that validate that if the number
is a prime number or not.
• Call this function in the main class by just passing the parameter (integer).
• Print the prime number.

package prime;

public class Program{


static void checkPrime(int n){
int i,m=0,flag=0;
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0) {
System.out.println(n+" is prime number");
}
}//end of else
}
public static void main(String args[]){
checkPrime(1);
checkPrime(3);
checkPrime(17);
checkPrime(20);
}
}

Program to display the prime numbers from 1 to 100

• In this case, use counter which is often required to understand the frequency of something from a
database or a text file.
• Declare an empty string, String primeNumbers = “”;
• Directly specify the actual number using a for loop. for(num =i; num>=1; num–) and check for
prime numbers in this range.
• If the given number is divisible by the input number, it increments the counter value.|
• If the counter value is 2, append the prime numbers in the form of a string.

package prime;

public class OneToN {


public static void main (String[] args)
{
int i =0;
int num =0;
//Empty String
String primeNumbers = "";

for (i = 1; i <= 100; i++) {


int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to 100 are :");
System.out.println(primeNumbers);
}
}

Output:

This brings us to the end of this article where we have learned the frequently asked questions on the
Prime number program in Java. Hope you are clear with all that has been shared with you in this tutorial.

Java Program to Find GCD of Two Numbers


The GCD (Greatest Common Divisor) of two numbers is the largest positive integer number that
divides both the numbers without leaving any remainder. For example. GCD of 30 and 45 is 15. GCD
also known as HCF (Highest Common Factor). In this tutorial we will write couple of different Java
programs to find out the GCD of two numbers.

How to find out the GCD on paper?


To find out the GCD of two numbers we multiply the common factors as shown in the following
diagram:

Example 1: Java Program to find GCD of two numbers using for loop

In this example, we are finding the GCD of two given numbers using for loop.

We are running a for loop from 1 to the smaller number and inside loop we are dividing both the
numbers with the loop counter “i” which ranges from 1 to the smaller number value. If the value of i
divides both numbers with no remainder then we are assigning that value to the variable “gcd”. At the
end of the loop, the variable “gcd” will have the largest number that divides both the numbers without
remainder.

public class GCDExample1 {

public static void main(String[] args) {

//Lets take two numbers 55 and 121 and find their GCD
int num1 = 55, num2 = 121, gcd = 1;

/* loop is running from 1 to the smallest of both numbers


* In this example the loop will run from 1 to 55 because 55
* is the smaller number. All the numbers from 1 to 55 will be
* checked. A number that perfectly divides both numbers would
* be stored in variable "gcd". By doing this, at the end, the
* variable gcd will have the largest number that divides both
* numbers without remainder.
*/
for(int i = 1; i <= num1 && i <= num2; i++)
{
if(num1%i==0 && num2%i==0)
gcd = i;
}

System.out.printf("GCD of %d and %d is: %d", num1, num2, gcd);


}

}
Output:

GCD of 55 and 121 is: 11


Example 2: Finding GCD of two numbers using while loop

Lets write the same program using while loop. Here we are taking a different approach of finding gcd. In
this program we are subtracting the smaller number from the larger number until they both become
same. At the end of the loop the value of the numbers would be same and that value would be the GCD
of these numbers.

public class GCDExample2 {

public static void main(String[] args) {

int num1 = 55, num2 = 121;

while (num1 != num2) {


if(num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}

System.out.printf("GCD of given numbers is: %d", num2);


}

Output:

GCD of given numbers is: 11

Example 3: Finding GCD of two input(Entered by user) numbers


In this example, we are using Scanner to get the input from user. The user would enter the value of both
the numbers and program would find the GCD of these entered numbers.

import java.util.Scanner;
public class GCDExample3 {

public static void main(String[] args) {

int num1, num2;

//Reading the input numbers


Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
num1 = (int)scanner.nextInt();
System.out.print("Enter second number:");
num2 = (int)scanner.nextInt();

//closing the scanner to avoid memory leaks


scanner.close();
while (num1 != num2) {
if(num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}

//displaying the result


System.out.printf("GCD of given numbers is: %d", num2);
}

}
Finding Greatest Common Divisor in Java
1. Overview

In mathematics, the GCD of two integers, which are non-zero, is the largest positive integer that
divides each of the integers evenly.

2. Brute Force

For our first approach, we iterate from 1 to the smallest number given and check whether the given
integers are divisible by the index. The largest index which divides the given numbers is the GCD of
the given numbers:

int gcdByBruteForce(int n1, int n2) {


int gcd = 1;
for (int i = 1; i <= n1 && i <= n2; i++) {
if (n1 % i == 0 && n2 % i == 0) {
gcd = i;
}
}
return gcd;
}

As we can see, the complexity of the above implementation is O(min(n1, n2)) because we need to iterate
over the loop for n times (equivalent to the smaller number) to find the GCD.

3. Euclid's Algorithm

Second, we can use Euclid's algorithm to find the GCD. Euclid's algorithm is not only efficient but also
easy to understand and easy to implement using recursion in Java.

Euclid's method depends on two important theorems:


• First, if we subtract the smaller number from the larger number, the GCD doesn't change –
therefore, if we keep on subtracting the number we finally end up with their GCD
• Second, when the smaller number exactly divides the larger number, the smaller number is the
GCD of the two given numbers.

Note in our implementation that we'll use modulo instead of subtraction since it's basically many
subtractions at a time:

int gcdByEuclidsAlgorithm(int n1, int n2) {


if (n2 == 0) {
return n1;
}
return gcdByEuclidsAlgorithm(n2, n1 % n2);
}

Also, note how we use n2 in n1‘s position and use the remainder in n2's position in the recursive step of
the algorithm.

Further, the complexity of Euclid's algorithm is O(Log min(n1, n2)) which is better as compared to
the Brute Force method we saw before.

4. Stein's Algorithm or Binary GCD Algorithm

Finally, we can use Stein's algorithm, also known as the Binary GCD algorithm, to find the GCD of
two non-negative integers. This algorithm uses simple arithmetic operations like arithmetic shifts,
comparison, and subtraction.

Stein's algorithm repeatedly applies the following basic identities related to GCDs to find GCD of two
non-negative integers:

1. gcd(0, 0) = 0, gcd(n1, 0) = n1, gcd(0, n2) = n2


2. When n1 and n2 are both even integers, then gcd(n1, n2) = 2 * gcd(n1/2, n2/2), since 2 is the common
divisor
3. If n1 is even integer and n2 is odd integer, then gcd(n1, n2) = gcd(n1/2, n2), since 2 is not the common
divisor and vice versa
4. If n1 and n2 are both odd integers, and n1 >= n2, then gcd(n1, n2) = gcd((n1-n2)/2, n2) and vice versa
5. We repeat steps 2-4 until n1 equals n2, or n1 = 0. The GCD is (2n) * n2. Here, n is the number of times 2
is found common in n1 and n2 while performing step 2:

int gcdBySteinsAlgorithm(int n1, int n2) {


if (n1 == 0) {
return n2;
}

if (n2 == 0) {
return n1;
}

int n;
//both n1 and n2 are even
for (n = 0; ((n1 | n2) & 1) == 0; n++) {
n1 >>= 1;
n2 >>= 1;
}
//if n1 is even
while ((n1 & 1) == 0) {
n1 >>= 1;
}

do {
//n2 is even
while ((n2 & 1) == 0) {
n2 >>= 1;
}

if (n1 > n2) {


int temp = n1;
n1 = n2;
n2 = temp;
}
n2 = (n2 - n1);
} while (n2 != 0);
return n1 << n;
}

We can see that we use arithmetic shift operations in order to divide or multiply by 2. Further, we use
subtraction in order to reduce the given numbers.

The complexity of Stein's algorithm when n1 > n2 is O((log2n1)2) whereas. when n1 < n2, it is
O((log2n2)2).

5. Conclusion

In this tutorial, we looked at various methods for calculating the GCD of two numbers. We also
implemented these in Java and had a quick look at their complexity.

How to find GCD of two numbers in Java - Euclid's algorithm


Simple Java program to find GCD (Greatest Common Divisor) or GCF (Greatest Common Factor) or HCF
(Highest common factor). The GCD of two numbers is the largest positive integer that divides both the
numbers fully i.e. without any remainder. There are multiple methods to find GCD, GDF or HCF of two
numbers but Euclid's algorithm is very popular and easy to understand, of course, only if you
understand how recursion works.

Euclid's algorithm is an efficient way to find GCD of two numbers and it's pretty easy to implement
using recursion in Java program. According to Euclid's method GCD of two numbers, a, b is equal to
GCD(b, a mod b) and GCD(a, 0) = a.
The latter case is the base case of our Java program to find GCD of two numbers using recursion. You
can also calculate the greatest common divisor in Java without using recursion but that would not be
as easy as the recursive version, but still a good exercise from the coding interview point of view.

It's very easy to understand this algorithm once you look at the flow chart, which explains how Euclid's
GCD algorithm works. You can also read Introduction to Algorithm by Thomas Cormen to learn more
about similar computer algorithms.

This is one of the most popular books to learn Data structure and algorithms and widely used as
textbooks for algorithms in many schools, colleges, and universities. It is also popularly known as CLRS
(Cormen, Leiserson, Rivest, Stein).

GCD of two numbers in Java Code Example:


In Euclid's algorithm, we start with two numbers X and Y.

✓ If Y is zero then the greatest common divisor of both will be X, but

✓ if Y is not zero then we assign the Y to X and Y becomes X%Y. Once again we check if Y is zero, if yes
then we have our greatest common divisor or GCD otherwise we keep continue like this until Y
becomes zero.

Since we are using the modulo operator, the number is getting smaller and smaller at each
iteration, so the X%Y will eventually become zero.

Let' take an example of calculating GCD of 54 and 24 using Euclid's algorithm. Here X = 54 and
Y = 24 since Y is not zero we move to the logical part and assign X = Y, which means X
becomes 24 and Y becomes 54%24 i.e 6.

Since Y is still not zero, we again apply the logic. This time X will become 6 and Y will become
24%6 i.e. Y=0. Bingo, Y is now zero which means we have our answer and it's nothing but the
value of X which is 6 (six).

The algorithm will become clearer when you see the flow chart of calculating GCD of two
numbers using recursion as shown below. You can see we are starting with two numbers X and
Y and if Y=0 then we got our answer, otherwise, we apply logic and check again.

Now let's learn how to convert Euclid's algorithm to find GCD into Java code.
Here is my complete code example of how to find GCD of two numbers in Java. This Java program uses Euclid's
method to find GCD of two numbers. Thy must be an integer, so make sure you check the numbers entered by the
user like floating-point numbers are not allowed.

Similarly, any alphabets and other characters are not allowed except '+' and '-' sign and all these rules are ensured
by Scanner.nextInt() call. This method will throw an error if the user will enter an invalid value instead of
an integer.

Java Program to calculate GCD of two numbers


/**
* Java program to demonstrate How to find Greatest Common Divisor or GCD of
* two numbers using Euclid’s method. There are other methods as well to
* find GCD of two number in Java but this example of finding GCD of two number
* is most simple.
*
* @author Javin Paul
*/
public class GCDExample {
public static void main(String args[]){

//Enter two number whose GCD needs to be calculated.


Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first number to find GCD");
int number1 = scanner.nextInt();
System.out.println("Please enter second number to find GCD");
int number2 = scanner.nextInt();

System.out.println("GCD of two numbers " + number1 +" and "


+ number2 +" is :" + findGCD(number1,number2));

/*
* Java method to find GCD of two number using Euclid's method
* @return GDC of two numbers in Java
*/
private static int findGCD(int number1, int number2) {
//base case
if(number2 == 0){
return number1;
}
return findGCD(number2, number1%number2);
}

Output:
Please enter first number to find GCD
54
Please enter second number to find GCD
24
GCD of two numbers 54 and 24 is :6
That’s all on how to find GCD of two numbers in Java. You can use this Java program to prepare for
viva or other computer homework and assignment test or for your self-practice to improve programming
in Java. BTW, there is a couple of other techniques to find Greatest common divisor in Java, as an
exercise you can explore those methods and write code for that. The key point is you need to learn how
to convert an algorithm into code to become a programmer.

Finding the Least Common


Multiple in Java
1. Overview

The Least Common Multiple (LCM) of two non-zero integers (a, b) is the smallest positive integer
that is perfectly divisible by both a and b.

In this tutorial, we'll learn about different approaches to find the LCM of two or more numbers. We
must note that negative integers and zero aren't candidates for LCM.

2. Calculating LCM of Two Numbers Using a Simple Algorithm


We can find the LCM of two numbers by using the simple fact that multiplication is repeated
addition.

2.1. Algorithm

The simple algorithm to find the LCM is an iterative approach that makes use of a few fundamental
properties of LCM of two numbers.

Firstly, we know that the LCM of any number with zero is zero itself. So, we can make an early exit
from the procedure whenever either of the given integers is 0.

Secondly, we can also make use of the fact that the lower bound of the LCM of two non-zero integers
is the larger of the absolute values of the two numbers.

Moreover, as explained earlier, the LCM can never be a negative integer. So, we'll only use absolute
values of the integers for finding the possible multiples until we find a common multiple.

Let's see the exact procedure that we need to follow for determining lcm(a, b):

1. If a = 0 or b = 0, then return with lcm(a, b) = 0, else go to step 2.


2. Calculate absolute values of the two numbers.
3. Initialize lcm as the higher of the two values computed in step 2.
4. If lcm is divisible by the lower absolute value, then return.
5. Increment lcm by the higher absolute value among the two and go to step 4.

Before we start with the implementation of this simple approach, let's do a dry-run to find lcm(12, 18).

✓ As both 12 and 18 are positive, let's jump to step 3, initializing lcm = max(12, 18) = 18, and
proceed further.
✓ In our first iteration, lcm = 18, which isn't perfectly divisible by 12. So, we increment it by 18
and continue.
✓ In the second iteration, we can see that lcm = 36 and is now perfectly divisible by 12. So, we can
return from the algorithm and conclude that lcm(12, 18) is 36.

2.2. Implementation
Let's implement the algorithm in Java. Our lcm() method needs to accept two integer arguments and give
their LCM as a return value.

We can notice that the above algorithm involves performing a few mathematical operations on the
numbers such as finding absolute, minimum, and maximum values. For this purpose, we can use the
corresponding static methods of the Math class such as abs(), min(), and max(), respectively.

Let's implement our lcm() method:

public static int lcm(int number1, int number2) {


if (number1 == 0 || number2 == 0) {
return 0;
}
int absNumber1 = Math.abs(number1);
int absNumber2 = Math.abs(number2);
int absHigherNumber = Math.max(absNumber1, absNumber2);
int absLowerNumber = Math.min(absNumber1, absNumber2);
int lcm = absHigherNumber;
while (lcm % absLowerNumber != 0) {
lcm += absHigherNumber;
}
return lcm;
}

Next, let's also validate this method:

@Test
public void testLCM() {
Assert.assertEquals(36, lcm(12, 18));
}

The above test case verifies the correctness of the lcm() method by asserting that lcm(12, 18) is 36.

4. Using the Euclidean Algorithm


There's an interesting relation between the LCM and GCD (Greatest Common Divisor) of two numbers
that says that the absolute value of the product of two numbers is equal to the product of their GCD
and LCM.

✓ As stated, gcd(a, b) * lcm(a, b) = |a * b|.


✓ Consequently, lcm(a, b) = |a * b|/gcd(a, b).

Using this formula, our original problem of finding lcm(a,b) has now been reduced to just finding
gcd(a,b).

Granted, there are multiple strategies to finding GCD of two numbers. However, the Euclidean
algorithm is known to be one of the most efficient of all.

For this reason, let's briefly understand the crux of this algorithm, which can be summed up in two
relations:

• gcd (a, b) = gcd(|a%b|, |a| ); where |a| >= |b|


• gcd(p, 0) = gcd(0, p) = |p|
Let's see how we can find lcm(12, 18) using the above relations:

We have gcd(12, 18) = gcd(18%12, 12) = gcd(6,12) = gcd(12%6, 6) = gcd(0, 6) = 6

Therefore, lcm(12, 18) = |12 x 18| / gcd(12, 18) = (12 x 18) / 6 = 36

We'll now see a recursive implementation of the Euclidean algorithm:

public static int gcd(int number1, int number2) {


if (number1 == 0 || number2 == 0) {
return number1 + number2;
} else {
int absNumber1 = Math.abs(number1);
int absNumber2 = Math.abs(number2);
int biggerValue = Math.max(absNumber1, absNumber2);
int smallerValue = Math.min(absNumber1, absNumber2);
return gcd(biggerValue % smallerValue, smallerValue);
}
}

The above implementation uses the absolute values of numbers — since GCD is the largest positive
integer that perfectly divides the two numbers, we're not interested in negative divisors.

We're now ready to verify if the above implementation works as expected:

@Test
public void testGCD() {
Assert.assertEquals(6, EuclideanAlgorithm.gcd(12, 18));
}

4.1. LCM of Two Numbers


Using the earlier method to find GCD, we can now easily calculate LCM. Again, our lcm() method
needs to accept two integers as input to return their LCM. Let's see how we can implement this method
in Java:

public static int lcm(int number1, int number2) {


if (number1 == 0 || number2 == 0)
return 0;
else {
int gcd = gcd(number1, number2);
return Math.abs(number1 * number2) / gcd;
}
}

We can now verify the functionality of the above method:

@Test
public void testLCM() {
Assert.assertEquals(36, EuclideanAlgorithm.lcm(12, 18));
}
5. Conclusion

In this tutorial, we discussed various methods to find the least common multiple of two numbers in Java.

Moreover, we also learned about the relation between the product of numbers with their LCM and GCD.
Given algorithms that can compute the GCD of two numbers efficiently, we've also reduced the problem
of LCM calculation to one of GCD computation.

Java Program to Find LCM of two Numbers


In this program, you'll learn to find the lcm of two number by using GCD, and by not using GCD. This
is done using for and while loops in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

• Java if...else Statement


• Java while and do...while Loop

The LCM of two integers is the smallest positive integer that is perfectly divisible by both the numbers
(without a remainder).

Example 1: LCM using while Loop and if Statement


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

int n1 = 72, n2 = 120, lcm;

// maximum number between n1 and n2 is stored in lcm


lcm = (n1 > n2) ? n1 : n2;

// Always true
while(true) {
if( lcm % n1 == 0 && lcm % n2 == 0 ) {
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
break;
}
++lcm;
}
}
}

Output

The LCM of 72 and 120 is 360.


In this program, the two numbers whose LCM is to be found are stored in variables n1 and n2
respectively.

Then, we initially set lcm to the largest of the two numbers. This is because, LCM cannot be less than
the largest number.

Inside the infinite while loop (while(true)), we check if lcm perfectly divides both n1 and n2 or not.

If it does, we've found the LCM. We print the LCM and break out from the while loop using break
statement.

Else, we increment lcm by 1 and re-test the divisibility condition.

We can also use GCD to find the LCM of two numbers using the following formula:

LCM = (n1 * n2) / GCD

If you don't know how to calculate GCD in Java, check Java Program to find GCD of two numbers.

Example 2: Calculate LCM using GCD


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

int n1 = 72, n2 = 120, gcd = 1;

for(int i = 1; i <= n1 && i <= n2; ++i) {


// Checks if i is factor of both integers
if(n1 % i == 0 && n2 % i == 0)
gcd = i;
}

int lcm = (n1 * n2) / gcd;


System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
}
}

The output of this program is the same as Example 1.

Here, inside the for loop, we calculate the GCD of the two numbers - n1 and n2. After the calculation,
we use the above formula to calculate the LCM.

Java Program to print Pascal Triangle


Java Example to print Pascal’s Triangle
In this program, user is asked to enter the number of rows and based on the input, the pascal’s triangle is
printed with the entered number of rows.

package com.beginnersbook;
import java.util.Scanner;
public class JavaExample {
static int fact(int num) {
int factorial;

for(factorial = 1; num > 1; num--){


factorial *= num;
}
return factorial;
}
static int ncr(int n,int r) {
return fact(n) / ( fact(n-r) * fact(r) );
}
public static void main(String args[]){
int rows, i, j;

//getting number of rows from user


System.out.println("Enter number of rows:");
Scanner scanner = new Scanner(System.in);
rows = scanner.nextInt();
scanner.close();

System.out.println("Pascal Triangle:");
for(i = 0; i < rows; i++) {
for(j = 0; j < rows-i; j++){
System.out.print(" ");
}
for(j = 0; j <= i; j++){
System.out.print(" "+ncr(i, j));
}
System.out.println();
}
}
}

What is Pascal’s Triangle – Java Implementation


Pascal Triangle is named after French mathematician Blaise Pascal. It is a triangular array of binomial
coefficients.

The triangle follows a very simple rule.

Each number is the sum of the two numbers directly above it.

Here’s a gif that illustrates filling of a pascal triangle.


The value of element (i,j) is given by C(i,j) = i!/((i-j)!*j!). Where i is the row number and j is the
element position in that row.

• 1 Java Code for Pascal’s Triangle


• 2 Code Breakdown
• 3 Output
• 4 Conclusion

Java Code for Pascal’s Triangle

The Java code to print a pascal triangle is as follows.

package com.JournalDev;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner s = new Scanner (System.in);
System.out.println("Enter the number of rows");
int rows = s.nextInt();
int coef = 1;

for(int i = 0; i < rows; i++) {

for(int sp = 1; sp < rows - i; ++sp) {


System.out.print(" ");
}

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


if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
System.out.printf("%4d", coef);
}

System.out.println();
}
}
}

The code inputs the number of rows of pascal triangle from the user.

Let’s go over the code and understand.

Code Breakdown

The outer most for loop is responsible for printing each row. It will run ‘row’ number of times.

for(int i = 0; i < rows; i++) {

The next for loop is responsible for printing the spaces at the beginning of each line.

for(int sp = 1; sp < rows - i; ++sp) {


System.out.print(" ");

We can see that as the current row number (i) increases, the number of times this loop runs will
decrease.

The next for loop is responsible for printing the numbers in the triangle.

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


if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;

System.out.printf("%4d", coef);

For first row and first element of each subsequent row, 1 is printed as the output.

The formula that computes the digit for the remaining positions is :

coef = coef * (i - j + 1) / j;

Where i is the current row number and j is the position of the element in that row.
j is initialised to 0 for each row.

We can do a quick dry run for row number 3.

i = 3, j = 0 -> 1 (coef)
i = 3, j = 1 -> 3 (1*(3-1+1)/1)
i = 3, j = 2 -> 3 (3*(3-2+1)/2)
i = 3, j = 3 -> 1 (3*(3-3+1)/3)

The row comes out to be :

1 3 3 1

You should do this for row munger 4 and 5 as well to understand how the formula works.

To format the output properly, we use printf.

Output

The output obtained after running the code is as follows :

Pascal Triangle for 6 rows

Pascal Triangle for 10 rows


Conclusion
This tutorial was about pascal triangle and how to write a code for generating it. Hope you understood
the concept and enjoyed learning about it!

Java program to print Pascal's triangle


Pascal's triangle is one of the classic example taught to engineering students. It has many interpretations.
One of the famous one is its use with binomial equations.

All values outside the triangle are considered zero (0). The first row is 0 1 0 whereas only 1 acquire a
space in Pascal’s triangle, 0s are invisible. Second row is acquired by adding (0+1) and (1+0). The
output is sandwiched between two zeroes. The process continues till the required level is achieved.

Algorithm

• Take a number of rows to be printed, n.


• Make outer iteration I for n times to print rows.
• Make inner iteration for J to (N - 1).
• Print single blank space " ".
• Close inner loop.
• Make inner iteration for J to I.
• Print nCr of I and J.
• Close inner loop.
• Print NEWLINE character after each inner iteration.

Example
public class PascalsTriangle {
static int factorial(int n) {
int f;

for(f = 1; n > 1; n--){


f *= n;
}
return f;
}
static int ncr(int n,int r) {
return factorial(n) / ( factorial(n-r) * factorial(r) );
}
public static void main(String args[]){
System.out.println();
int n, i, j;
n = 5;

for(i = 0; i <= n; i++) {


for(j = 0; j <= n-i; j++){
System.out.print(" ");
}
for(j = 0; j <= i; j++){
System.out.print(" "+ncr(i, j));
}
System.out.println();
}
}
}
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Pascal Triangle

In mathematics, the Pascal's Triangle is a triangle made up of numbers that never ends. The Pascal's
Triangle was first suggested by the French mathematician Blaise Pascal, in the 17th century. He had
used Pascal's Triangle in the study of probability theory. After that it has been studied by many scholars
throughout the world.

In this section, we will learn what is Pascal's Triangle, its uses, formula, and properties.

What is Pascal's Triangle?

Pascal's Triangle is a never-ending equilateral triangle in which the arrays of numbers arranged in a
triangular manner. The triangle starts at 1 and continues placing the number below it in a triangular
pattern. Remember that Pascal's Triangle never ends.

In Pascal's Triangle, each number is the sum of the two numbers above it.

Formula

We can find any entry of the Pascal's Triangle by using the Combination formula.
In the above formula, nCr )means choose r from n. We can also write nCr as C(n,r),nCr.

Where,

n: is the size of the set (the total number of items in the sample).

C: is the combination.

r: is the subset size (the number of items to be selected from the sample)

Sometimes, we also use k instead of r. Therefore, we can write the above formula in terms of n and k,
as:

Let's find some entries of the Pascal's Triangle by using the above formula.

Example: Find the entry of 4th row's 4th term.

Solution:

We have to find the entry of the 4th row's 4th term. Here, n=4 and r=4.

Putting the values of n and r in the formula, we get:


Hence, the 4th term of the 4th row is 1.

Example: Find the entry of the 6th row's 5th term.

Solution:

We have to find the entry of 6th row's 5th term. Here, n=6 and r=5.

Putting the values of n and r in the formula, we get:

Hence, the 5th term of the 6th row is 6.

Similarly, we can find any entry of the Pascal's Triangle, directly.

Pascal’s triangle has many unique properties e.g. the sum of numbers in each row is twice the sum of numbers in
the above row and the diagonals adjacent to the border diagonals contains natural numbers in order. Pascal
triangle is also related to Fibonacci series, if you add the numbers in Pascal's triangle in diagonal lines going up,
you get one of the Fibonacci numbers. Even though the post is about printing the Pascal's triangle but a bit
history always helps.

How to check leap year in Java - program example


Write a Java program to find if a year is a leap year or not is a standard Java programming exercise
during various Java programming course on school, colleges and various training institutes both online and
offline, along with other popular homework's e.g. printing Fibonacci numbers, checking palindromes or
finding prime numbers. Just to recap a leap year is a year with 366 days which is 1 extra day than a normal
year. This extra day comes in the month of February and on leap year Feb month has 29 days than normal
28 days. If you are following then you might know that leap year comes in an interval of 4 years. This year
2012 is a leap year and Feb has 29 days, you can check.

Now if you are in programming before you might be familiar that there is standard logic to find leap year
i.e.
✓ if an year is multiple of 400 or
✓ multiple of 4 but not multiple of 100 then its a leap year.

In addition to this standard logic, you can also use Java's Date, Time and Calendar API to check how many
days any year has and by comparing that number with 365 you can find whether that year is leap year or
not .

In this Java programming tutorial we will both of these example to check if a year is leap year or not.

Java program to check if a year is leap year

Here is complete code example of Java program to find out whether an year is leap year or not.
isLeapYear(int year) method uses Calendar API to get maximum number of days in that year and compare
that with 365. If year contains more than 365 days, its a leap year. Second method doesLeapYear(int year)
uses programming logic to find if year is leap or not.

package test;

import java.util.Calendar;

/**
*
* Java program to find if a year is leap year or not.
* A leap year is a year which contains 366 day, which is 1 day more of normal 365 day year.
* Leap year comes in a interval of 4 years. In Gregorian
* calendar in leap year February has 29 days which is 1 day more than 28 day in normal year.
*
* @author
*/
public class LeapYearProgram {

public static void main(String args[]) {

//Testing some leap and non leap year using Java library code
System.err.println("Is 2000 a leap year ? : " + isLeapYear(2000));
System.err.println("Is 2012 a leap year ? : " + isLeapYear(2012));
System.err.println("Is 1901 a leap year ? : " + isLeapYear(1901));
System.err.println("Is 1900 a leap year ? : " + isLeapYear(1900));

//Checking leap year without using library or API and applying logic
System.err.println("Does 2000 a leap year : " + doesLeapYear(2000));
System.err.println("Does 2012 a leap year : " + doesLeapYear(2012));
System.err.println("Does 1901 a leap year : " + doesLeapYear(1901));
System.err.println("Does 1900 a leap year : " + doesLeapYear(1900));
}
/*
* This method checks whether a year is leap or not by using Java Date
* and Time API. Calendar class has utility method to return maximum
* number of days in a year which can be used to check if its
* greater than 365 or not
*/
public static boolean isLeapYear(int year){
Calendar cal = Calendar.getInstance(); //gets Calendar based on local timezone and locale
cal.set(Calendar.YEAR, year); //setting the calendar year
int noOfDays = cal.getActualMaximum(Calendar.DAY_OF_YEAR);

if(noOfDays > 365){


return true;
}

return false;
}

/*
* This method uses standard logic to check leap year in Java.
* A year is a leap year if its multiple of 400 or multiple of 4 but not 100
*/
public static boolean doesLeapYear(int year){
return (year%400 == 0) || ((year%100) != 0 && (year%4 == 0));
}
}

Output:
Is 2000 a leap year ? : true
Is 2012 a leap year ? : true
Is 1901 a leap year ? : false
Is 1900 a leap year ? : false
Does 2000 a leap year : true
Does 2012 a leap year : true
Does 1901 a leap year : false
Does 1900 a leap year : false
Java Program to Print Alphabets in Upper and
Lower Case
One of the textbook exercise to get start with any programming language is writing a program to
print alphabets in both upper and lower case. This program allows you to explore the String class
in Java with toUpperCase() and toLowerCase() method but normally when you start, it's asked to
do this without any API methods. This kind of exercise actually improves your understanding of
programming language e.g. basic operators, data types like int and char. It's similar to your prime
number, Fibonacci series, and factorial program exercise. I strongly suggest doing this textbook
exercises to anyone who is just started learning a new programming language. Coming back to this
program, Java has a datatype called char, which is 2-byte unsigned integer type. It is used to store
characters in Java e.g. char A = 'A'.

Similar to String literal "A" we also have character literal 'A' which is letters enclosed in single
quotes. There is worth-noting difference between storing character literal in char and int data
type in Java. If you store character literal on integer variable e.g. int i = 'a'; will store ASCII value of
'a' and when you print, it will prints ASCII value of 'a'.

How to print alphabets in upper and lower case

Here is our complete Java program to print characters in upper and lower case. It's simple program without using
any API method. We have two methods printAlphabets() and printAlphabetsInUpperCase(), I
have made them static method so that I can call them directly from main method, which is a static method. Why?
because you can not call a non-static method from static context in Java.

If you look at these methods, they are most simplest, you will ever see, of-course apart form HelloWorld
in Java. Their is a loop in each of these method which print value of character in each iteration and runs
until it reaches last character of alphabets in each case.

/**
*
* Java program to print alphabets in both upper and lower case.
*
* @author http://java67.blogspot.com
*/
public class PrintAlphabetsInJava{

public static void main(String args[]) {

// printing alphabets in lower case i.e. 'a' to 'z'


printAlphabets();

// printing alphabets in upper case i.e. 'A' to 'Z'


printAlphabetsInUpperCase();
}

public static void printAlphabets() {


System.out.println("List of alphabets in lowercase :");
for (char ch = 'a'; ch <= 'z'; ch++) {
System.out.printf("%s ", ch);
}
}

public static void printAlphabetsInUpperCase() {


System.out.println("\nList of alphabets in upper case :");
for (char ch = 'A'; ch <= 'Z'; ch++) {
System.out.printf("%s ", ch);
}
}

Output
List of alphabets in lowercase :
a b c d e f g h i j k l m n o p q r s t u v w x y z
List of alphabets in upper case :
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

That's all on how to print alphabets on lower and upper case in Java. You can ever try to do this task in
different way, try using different loop e.g. while, for-each or do-while. You can also try following
programming exercise to get some more practice.
How to Reverse digits of an Integer in Java without
converting to String
Hello guys, LeetCode has a problem to reverse digits of an integer number without using any library method like
the reverse() method of StringBuffer. In LeetCode, you can solve this problem with many different languages
like Java, C, C++, C#, Python, Ruby, and even JavaScript. in the article, you will learn how to solve this problem
in Java. Before approaching a solution let's first read the problem statement :

Reverse digits of an integer.

Example 1: x = 123, return 321


Example 2: x = -123, return -321

The problem looks simple but it's not simple there are many things you need to consider in order to produce a
solution that is accepted by LeetCode, which has thousands of test cases to test your solution.

For example, you need to consider not just a positive integer but also a negative integer. Remember, a positive
integer can also be written using the + sign, so you need to handle that as well. If the integer's last digit is 0, what
should the output be? I mean, cases such as 10, 100.

If the return type of method is an integer then you can simply return 1, it's perfectly ok, but if the return type
of method is String then you may need to return 001 or 0001. For the purpose of this solution, we expect our
method to return an integer, so 1 is fine.

By the way, if you are preparing for coding interviews then you should be prepared for such kinds of questions.
According to Leetcode, this is one of the common coding problems from Google interviews.

How to Reverse digits of an Integer in Java without converting to String?


Here are my algorithms to solve this problem of reversing integer numbers without using any direct library
method.

The crux of this problem is how to use division and modulo operators in Java to get the last digit of a number and
get rid of the last digit as well.

If you remember, I have shared this trick before when I was explaining how to use a modulo operator in Java.
This is a really neat trick and will help you to solve many programming problems where you need to divide
numbers into individual digits.

When you divide a number by 10, you get rid of the last digit, for example, 211/10 will give you 21, and
21/10 will give you 2, so you got rid of the last 2 digits by dividing your number by 10 twice.

Similarly, you can use number modulo 10 to get the last digit of the number, for example, 221%10 will return
1, which is the last digit and 22%10 will return 2, which is the last digit of 22. You can apply this logic until you
processed the last digit.

Now the question comes, how do you arrange those digits in reverse order? Well, you can use just the
opposite, I mean, multiplication and addition to creating a new number with digits of the old number in reverse
order. I have used the following logic to assemble digits into reverse order :

reverse = reverse * 10 + lastDigit;

You can see by multiplying a number by 10 you increase the number of digits by 1 and then add the last digit. For
negative numbers, we multiply it by -1 to first make it positive and then apply the same logic, while returning
number we just multiply it by -1 again to convert the reversed number into negative.

This kind of little tricks really helps to solve coding problems during interviews and in your day-to-day life. If
you want to learn more of such patterns to boost your problem-solving skills then I also suggest you check
out Grokking the Coding Interview: Patterns for Coding Questions course on Educative.

This course will teach you 6 essential coding patterns like Sliding Window, Two Pointers, Fast and Slow Pointers,
Merge Intervals, Cyclic Sort, and Top K elements that can help you to solve zones of frequently asked coding
problems.

This is very good for preparing coding interviews as well as improving your coding skills. You can either buy this
course or take an Educative subscription for $18 per month to gain all of their quality courses like Grokking the
System design interview, which is a great deal.

Java Program to reverse an Integer without using String


Here is our complete Java program to reverse a given Integer without using String. As explained in the above
paragraph, I have used the Arithmetic and modulus operator to solve this problem.

import java.util.Scanner;
/**
* Java Program to reverse Integer in Java, number can be negative.
* Example 1: x = 123, return 321
* Example 2: x = -123, return -321
*
* @author Javin Paul
*/

public class ReverseInteger{

public static void main(String args[]) {


int input = 5678;
int output = reverseInteger(5678);
System.out.println("Input : " + input + " Output : " + output);
}

/*
* Java method to reverse an integer value. there are couple of
* corner cases
* which this method doesn't handle e.g. integer overflow.
*/
public static int reverseInteger(int number) {
boolean isNegative = number < 0 ? true : false;
if(isNegative){
number = number * -1;
}
int reverse = 0;
int lastDigit = 0;

while (number >= 1) {


lastDigit = number % 10; // gives you last digit
reverse = reverse * 10 + lastDigit;
number = number / 10; // get rid of last digit
}
return isNegative == true? reverse*-1 : reverse;
}

Result :
Input : 5678 Output : 8765

You can see that output is the just reverse of input. The first digit has exchanged position with the last digit, the
second with the second last, and so on.

By the way, if you are solving LeetCode problems as part of your interview preparation then you can also see The
Coding Interview Bootcamp and Cracking the Coding Interview, two of the most useful books and courses for
preparing programming job interviews. You will learn more in a short time.

import org.junit.*;
import static org.junit.Assert.*;
/**
* JUnit test four our solution to problem of reverse Integer in Java.
*
* @author WINDOWS 8
*
*/
public class ReverseIntegerTest{

@Test
public void testZeroAndOne(){
assertEquals(0, ReverseIntegerTest.reverseInteger(0));
assertEquals(1, ReverseIntegerTest.reverseInteger(1));
}

@Test
public void testSimple(){
assertEquals(4321, ReverseIntegerTest.reverseInteger(1234));
}
@Test
public void testNegative(){
assertEquals(-321, ReverseIntegerTest.reverseInteger(-123));
}

@Test
public void testNumberWithSign(){
assertEquals(321, ReverseIntegerTest.reverseInteger(+123));
}

@Test
public void testNumberEndingWithZero(){
assertEquals(1, ReverseIntegerTest.reverseInteger(1000));
assertEquals(1, ReverseIntegerTest.reverseInteger(10));
}

and here is the result of running these JUnit test case in Eclipse :

You can see that lovely green bar, which means all five tests are passed.
Hint: Leetcode is OK if your function returns 0 when the reversed integer overflows. Since our code doesn't
handle integer overflow like this, I left this as an exercise for you guys to fix.

That's all about how to reverse Integer in Java. By the way, this solution is prone to integer overflow and will
not be expected at Leetcode. It only managed to pass 1028 test cases out of staggering 1032 tests and failed for
input 1534236469. The expected solution, in that case, is zero but our program print something else, see if you
can spot the bug and fix it.
boot camp

1. A training camp for military recruits.


2. A correctional method, usually applied to youthful offenders, that employs strict disciplinary techniques and
rigorous physical training analogous to those used with military recruits.
3. An intensive training program, as for improving one's physical fitness or skills in a particular subject area.

boot camp
1. slang US a basic training camp for new recruits to the US Navy or Marine Corps
2. (Sociology) a centre for juvenile offenders, with a strict disciplinary regime, hard physical exercise, and
community labour programmes
boot camp - camp for training military recruits
bivouac, camp, cantonment, encampment - temporary living quarters specially built by the army for soldiers;
"wherever he went in the camp the men were grumbling"
armed forces, armed services, military, military machine, war machine - the military forces of a nation; "their
military is the largest in the region"; "the military machine is the same one we faced in 1991 but now it is weaker"
Boot Camp: Software from Apple that enables an Intel-based Mac to host the Windows operating system.
Boot Camp divides the hard disk into Windows and Mac partitions, installs the necessary drivers and
creates a "dual boot" environment. Introduced in 2006, Boot Camp does not provide a virtual machine
capability such as found in Parallels Desktop and VMware Fusion (see Mactel). Windows and Mac
applications are not run simultaneously. At startup, the user must choose which OS to use and must reboot
to switch to the other environment. See boot and dual boot.

boot camp
(colloquial) Initial, basic indoctrination, physical fitness training and basic instruction in service-related subjects
for new recruits in the armed forces
A short, intensive, quasi-military program generally aimed at young offenders as an alternative to a jail term.
(idiomatic) Any short, intensive course of training.
We will institute a boot camp for training the sales force in these new products.
The definition of boot camp is a military fitness and training camp.

• An example of boot camp is the first eight weeks in a soldier's military career, their basic training.
• The soldier was sent home from boot camp after he received another censure from the general.
• One of my most successful programs is the Beauty Boot Camp.
• A boot camp program provides troubled teens a military-style training in obeying authority.
• Many boot camp settings in foreign countries can cost less than their counterparts in the United States.
• Generally, boot camp is most effective with pre-teens or teenagers who just started acting out because it's
a short session.

Indoctrination meaning
The act of indoctrinating, or the condition of being indoctrinated.
Instruction in the rudiments and principles of any science or belief system; information.
How to Check is given String is a Palindrome in
Java using Recursion
In this tutorial, you will learn how to check if a string is a palindrome in Java using Recursion. A String is
nothing but a collection of characters like "Java," and String literals are encoded in double-quotes in Java.

A String is said to be a palindrome if the reverse of String is equal to itself like "aba" is a palindrome
because the opposite of "aba" is also "aba", but "abc" is not a palindrome because the reverse of "abc" is
"cba" which is not equal. Recursion means solving a problem by writing a function which calls itself. In
order to check if String is a palindrome in Java, we need a function that can reverse the String.

Once you have original and reversed String, all you need to do is check if they are equal to each other or
not. If they are equal then String is palindrome or not. You can write this reverse() function by using either
for loop or by using Recursion.

If you remember, I already shared the logic of reversing String in my earlier post, how to reverse String in
Java using Iteration and Recursion. Here we will use the same logic to check if String is palindrome or not.

Java Program to check if String is Palindrome Using Recursion


Here is our Java program, which checks if a given String is palindrome or not. Program is simple, and here are
steps to find palindrome String :

1) Reverse the given String


2) Check if the reverse of String is equal to itself; if yes, then given String is a palindrome.

In our solution, we have a static method isPalindromeString(String text), which accepts a String. It
then calls the reverse(String text) method to reverse this String. This method uses Recursion to reverse
String. This function first checks if given String is null or empty, if yes then it returns the same String because
they don't require to be reversed.

After this validation, it extracts the last character of String and passes rest or String using substring() method
to this method itself, hence the recursive solution. The validation also servers as base case because, after every
step, String keeps getting reduced, and eventually it will become empty, there your function will stop Recursion
and will use String concatenation to concatenate all character in reverse order. Finally, this method returns the
reverse of String.

When the call to reverse() returns back, isPalindromeString(String text) uses equals() method
to check if the reverse of String is equal to original String or not, if yes then it returns true, which also means
String is a palindrome.

How to check if String is Palindrome in Java using Recursion


Here is the complete Java program to check if given String is palindrome or not. In this program, we have used
Recursion to first reverse the String and then check if both original and reversed String is the same or not.

package test;

/**
* Java program to show you how to check if a String is palindrome or not.
* An String is said to be palindrome if it is equal to itself after reversing.
* In this program, you will learn how to check
* if a string is a palindrome in java using recursion
* and for loop both.
*
* @author Javin
*/
public class PalindromeTest {

public static void main(String args[]) {


System.out.println("Is aaa palindrom?: "
+ isPalindromString("aaa"));
System.out.println("Is abc palindrom?: "
+ isPalindromString("abc"));

System.out.println("Is bbbb palindrom?: "


+ isPalindromString("bbbb"));
System.out.println("Is defg palindrom?: "
+ isPalindromString("defg"));

/**
* Java method to check if given String is Palindrome
* @param text
* @return true if text is palindrome, otherwise false
*/
public static boolean isPalindromString(String text){
String reverse = reverse(text);
if(text.equals(reverse)){
return true;
}

return false;
}

/**
* Java method to reverse String using recursion
* @param input
* @return reversed String of input
*/
public static String reverse(String input){
if(input == null || input.isEmpty()){
return input;
}
return input.charAt(input.length()- 1)
+ reverse(input.substring(0, input.length() - 1));
}

Output
Is aaa palindrom?: true
Is abc palindrom?: false
Is bbbb palindrom?: true
Is defg palindrom?: false
How to check if String is Palindrome using StringBuffer and For loop
You can also solve this problem by retrieving character array from String using the toCharArray() and using
a for loop and StringBuffer. All you need to do is iterate through character array from end to start i.e. from the last
index to the first index and append those characters into the StringBuffer object. Once this is done, just call
the toString() method of StringBuffer, it's your reversed String.

Here is how your code will look like :

import java.util.Scanner;

/**
* How to check if String is palindrome in Java
* using StringBuffer and for loop.
*
* @author java67
*/

public class Palindrome{

public static void main(String args[]) {

Scanner reader = new Scanner(System.in);


System.out.println("Please enter a String");
String input = reader.nextLine();

System.out.printf("Is %s a palindrome? : %b %n",


input, isPalindrome(input));

System.out.println("Please enter another String");


input = reader.nextLine();

System.out.printf("Is %s a palindrome? : %b %n",


input, isPalindrome(input));

reader.close();
}

public static boolean isPalindrome(String input) {


if (input == null || input.isEmpty()) {
return true;
}

char[] array = input.toCharArray();


StringBuilder sb = new StringBuilder(input.length());
for (int i = input.length() - 1; i >= 0; i--) {
sb.append(array[i]);
}

String reverseOfString = sb.toString();

return input.equals(reverseOfString);
}

The devil is in the detail


is an idiom that refers to a catch or mysterious element hidden in the details, meaning that
something might seem simple at a first look but will take more time and effort to complete than
expected and derives from the earlier phrase,
"God is in the detail" expressing the idea that whatever one does should be done thoroughly;
i.e. details are important.
the devil is in the detail
• It means that when you do not concentrate on the details of something you may run into
unexpected problems
• Problems on large projects can often be attributed to small mistakes that were overlooked

Example Sentences

1. "Have you seen my beautiful new bag? I paid a fortune for it."
"Really? It is a fake. The stitching of the original bags is blue, not green."
"How disappointing. I guess the devil is in the details."
2. You need to make sure that your lawyer reads the contracts very carefully. The devil is in the
details.

How to reverse words in String Java?


In this Java Coding tutorial, you will learn how to reverse words in String. It's also one of the popular coding
questions, so you will also learn how to take a requirement, how to fill gaps in the requirement by asking the right
question. A String is nothing but a sentence, which may contain multiple words, or just contain a single word or it
may be empty. Your program must produce a String contains the word in reverse order, for example, if given
input is "Java is Great" then your program should return "Great is Java". Now, if you are a good programmer then
you should have some right questions for the programmer.

Never assume you know everything, even if it looks a simple problem. Always remember "Devil is in detail".
Also asking a question not only fill the gaps in requirement but also help you to make an impression.

Reversing the order of words in a Sentence in Java


Here is our Java solution to this problem. It's simple and straight forward. In this code example, I have shown
two ways to reverse words in a String, first one is using, Java's regular expression support to split the string into
spaces and then using reverse() method of Collections utility class. Once you split
the String using regex "\\s", it will return you an array of words. It will also handle words separated by
multiple spaces, so you don't need to worry.

Once you got the array, you can create an ArrayList from an array, and then you are eligible to use
Collections.reverse() method. This will reverse your ArrayList and you will have all the words in
reverse order, now all you need to do is concatenate multiple String by iterating over ArrayList.

I have used StringBuilder for concatenating String here. Also make sure to specify size, because resizing of
StringBuilder is costly as it involves the creation of a new array and copying content from old to the new array.

The second method is, even more, easier, instead of using Collections.reverse() method, I have just
used traditional for loop and started looping over array from the end and performing String concatenation. This
way, you even don't need to convert your String array to ArrayList of String. This solution is more memory
efficient and faster than the previous one.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
* Java Program to reverse words in String. There are multiple way to solve this
* problem. you can either use any collection class like List and reverse the
* List and later create reverse String by joining individual words.
*
* @author Javin Paul
*/
public class Testing {

public static void main(String args[]) {

}
/*
* Method to reverse words in String in Java
*/
public static String reverseWords(String sentence) {
List< String> words = Arrays.asList(sentence.split("\\s"));
Collections.reverse(words);
StringBuilder sb = new StringBuilder(sentence.length());

for (int i = words.size() - 1; i >= 0; i--) {


sb.append(words.get(i));
sb.append(' ');
}

return sb.toString().trim();
}

public static String reverseString(String line) {


if (line.trim().isEmpty()) {
return line;
}

StringBuilder reverse = new StringBuilder();


String[] sa = line.trim().split("\\s");

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


reverse.append(sa[i]);
reverse.append(' ');
}

return reverse.toString().trim();
}
}
}
Sometime Interviewer may ask you to solve this problem without using the Java Collection framework because it
obviously makes the task a lot easier. So its also good to prepare a solution based upon pure programming logic.
If you know how to reverse an array in Java, then you have an advantage because String is nothing but a character
array, but the tricky part is you don't need to reverse array but to reverse words.

That's all about how to reverse words in a String sentence in Java. You have learned two ways to reverse the
order of words. You have also learned how to split String using regex, which is an important skill for Java
programmer and you have also learned a good utility method to reverse any Collection in Java. It's good to
practice this kind of coding problem both to learn Java and to improve your programming and coding skills.

How to solve FizzBuzz in Java?


FizzBuzz is one of the most frequently asked questions on programming interviews and used to filter
programmers who can't program. It looks extremely simple but it's tricky for those programmers or coder who
struggle to structure their code. Fizzbuzz problem statement is very simple, write a program which return "fizz" if
the number is a multiplier of 3, return "buzz" if its multiplier of 5 and return "fizzbuzz" if the number is divisible
by both 3 and 5. If the number is not divisible by either 3 or 5 then it should just return the number itself. You can
see nothing is fancy when it comes to thinking about the solution, but when you start coding, you will see a
problem with structuring your code, particularly if else blocks.

First solution of FizzBuzz Problem


Many programmers come up with the following solution when first faced with Fizzbuzz problem :

public static String fizzBuzz(int number) {


if (number % 3 == 0) {
if (number % 5 == 0) {
return "fizzbuzz";
} else {
return "fizz";
}
} else if (number % 5 == 0) {
return "buzz";
}
return String.valueOf(number);
}
If you look at this solution closely you will find that the structure of the if statements is not good, and there are
two tests for the same condition i.e. two if block to check if the number is divisible by 5. The problem is the code
is not good but you should give the benefit of the doubt to the programmer because even though a test of 5 is
written twice they are in different branches, and only one of them will execute, but I agree the code is not clean.

Second solution of FizzBuzz


They key of coming with perfect solution is coming up with an approach to do the test for divisible by both 3 and
5 first. This brings more readability without duplication, as shown here

public static String fizzBuzz2(int number) {

if (number % 15 == 0) {
return "fizzbuzz";
} else if (number % 5 == 0) {
return "buzz";
} else if (number % 3 == 0) {
return "fizz";
}
return String.valueOf(number);
}

You can see that it's much cleaner even though it is also doing the test twice, but it's more pleasing to the eye and
straightforward.

Java Program to solve FizzBuzzProblem


Here is our complete Java program which combines both approaches to solving the fizzbuzz problem. We also
have some unit tests to verify our solution meets the problem statements.

import org.junit.Test;
import static org.junit.Assert.*;
/**
* Java Program to solve FizzBuzz problem
*
* @author WINDOWS 8
*
*/
public class FizzBuzzTest {
/**
* Java Method to solve FizzBuzz problem, which states that program
* should print fizz if number is multiple of 3,
* print buzz if number is multiple
* of 5, and print fizzbuzz if number is multiple of both 3 and 5
*
* @param number
* @return
*/
public static String fizzBuzz(int number) {

if (number % 3 == 0) {
if (number % 5 == 0) {
return "fizzbuzz";
} else {
return "fizz";
}
} else if (number % 5 == 0) {
return "buzz";
}
return String.valueOf(number);
}

/**
* An improved version of earlier solution, much cleaner than previous
* version because we have tested for divisible by 3 and 5 first.
* It avoid duplication also.
*/
public static String fizzBuzz2(int number) {
if (number % 15 == 0) {
return "fizzbuzz";
} else if (number % 5 == 0) {
return "buzz";
} else if (number % 3 == 0) {
return "fizz";
}
return String.valueOf(number);
}

@Test
public void testFizzBuzz(){
assertEquals("fizz", fizzBuzz(3));
assertEquals("buzz", fizzBuzz(5));
assertEquals("fizzbuzz", fizzBuzz(15));
assertEquals("2", fizzBuzz(2));
}

@Test
public void testFizzBuzzV2(){
assertEquals("fizz", fizzBuzzV2(3));
assertEquals("buzz", fizzBuzzV2(5));
assertEquals("fizzbuzz", fizzBuzzV2(15));
assertEquals("2", fizzBuzzV2(2));
}
}
Test Result :
All Pass

That's all about how to solve FizzBuzz Problem in Java. Sometime FizzBuzz is also asked as following
problem statement, write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz”
instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three
and five print “FizzBuzz". So don't confuse there, same logic works fine.
How to Find Missing Number in a Sorted Array in Java
Today's coding problem is not very new, it's an age-old classic Programming interview Question. You have a
sorted array containing n - 1 unique number starting from 0 to n - 1. There is only one number missing in this
range and you need to find that out. I mean you need to write a Java method to find the missing number and print
its value in the console. Some of you might have seen this question before, but if you have not been asked this
question before, what is the first approach comes into your mind to solve this question? Since only one number is
missing, many programmers come up with the approach of iterating over the array, and comparing each element
with the expected one like the first element should be 0, the second element should be 1, and so on.

Though this will solve the problem, it will cost you O(n) time. I mean time complexity of your solution would be
O(n) which is not good for a big array like with 100 million entries. What can you do to improve performance?

The key here is that you already have a sorted array, do you think our earlier solution is taking full
advantage of this knowledge, well it is but not fully.
What it is doing is performing a linear search which is costing O(n), but if you do a binary search, which of
course needs a sorted array, we can reduce the time taken in the range of O(logN).

Since numbers are in the range from 0 to n - 1 and are sorted, the first number till the missing one should be the
same as their indexes. I mean if 0 is not missing, then it must be in the first index, I mean at 0.

If you generalize this, you will find out that if the missing number is k then all numbers less than k is located in an
array with indexes the same as their value.

Also, number k + 1 will be located at index k, and number k + 2 will be located at index k + 1. What does this
mean? Well, it means that the missing number is the first cell whose value is not the same as its index. So our
problem reduces to search in an array to find the first cell, whose value is not the same as its index.

You can easily find out this by using the binary search algorithm in O(logN) time. Our solution implements this
logic to find the missing integer in a sorted array in Java. You can use this solution to find the missing number in
an array of numbers 1-1000 or 1 -100.

How to Find Missing Number in Sorted Array- Solution


Here is our complete solution to this problem. As discussed in the first paragraph, the solution is based upon a
binary search algorithm and that's why it's complexity is in logarithmic order. If you asked this question in the
interview, you must write production-quality code, what this means is handling invalid input and boundary
conditions.

In our method, we are checking whether the array is not null and empty before proceeding further. If you are not
familiar with the binary search algorithm than this diagram will help you how does it work. In binary search,
instead of starting from the front, we start from the middle element.

If the middle element is greater than the expected number is on the left-hand side of a middle element
(lower array), otherwise, it is on the right-hand side (higher array). So in each iteration, we end up reducing
our problem set by half.

So in the start, if you have 16 elements in the array, next iteration you only need to search in 8 elements and
subsequently 4 and 2, this is how we get O(logN) complexity. This problem also shows that knowledge of
coding patterns is very important for coding interviews.

If you know the pattern you can solve many unseen problems and that's why you should spend some time-solving
coding problems to build that pattern recognition logic in your mind.
Java Program to find the missing number in a sorted Integer array
And, here is our code example to find the missing integer in a sorted array or series.

import java.util.Arrays;
/**
* Java Program to find the missing number in a sorted array
* with integers in range 0 to n -1
*
* @author Javin Paul
*/
public class MissingNumberFinder {

public static void main(String args[]) {

System.out.println("Test #1 : Missing number in sorted array ");


int[] input = new int[]{1, 2, 3, 4, 6};
int missing = missingNumberFromSortedArray(input);
System.out.println("Missing number from array : "
+ Arrays.toString(input) + " is : " + missing);

public static int missingNumberFromSortedArray(int[] numbers) {


if (numbers == null || numbers.length <= 0) {
throw new IllegalArgumentException("Null or Empty array not permitted" );
}

int left = 0;
int right = numbers.length - 1;
while (left <= right) {
int middle = (right + left) >> 1;
if (numbers[middle] != middle) {
if (middle == 0 || numbers[middle - 1] == middle - 1) {
return middle;
}
right = middle - 1;
} else {
left = middle + 1;
}
}
throw new RuntimeException("No missing number");
}
}

Output:
Test #1 : Missing number in sorted array
Missing number from array : [1, 2, 3, 4, 6] is : 0

That's all about how do you find the missing integer in an array of 0 to n - 1. Remember you can also solve this
problem with linear search and there is nothing wrong if you first come up with that solution, in fact, it's very
natural, but you must pay attention to the sorted word. Binary search and sorted array go hand in hand. When it
comes to improving the search algorithms, binary search always better than linear search.

Insertion Sort Algorithm in Java with Example


Insertion sort is another simple sorting algorithm like Bubble Sort. You may not have realized but you must have
used Insertion sort in a lot of places in your life. One of the best examples of Insertion sort in the real-world is,
how you sort your hand in playing cards. You pick one card from the deck, you assume it's sorted, and then we
insert subsequent cards in their proper position. For example, if your first card is Jack, and the next card is Queen
then you put the queen after Jack. Now if the next card is King, we put it after the queen, and if we get 9, we put it
before jack.

So if you look closely, Insertion sort is a perfect sorting algorithm to insert a new value into an already
sorted array. That's why the best-case complexity of insertion sort is O(n), in which case you can just insert a
new number in the already sorted list of integers.

Another thing to keep in mind is the size of the list, insertion sort is very good for small list or array, but not so for
a large list, where QuickSort, MergeSort, and HeapSort rules.

Let's see one more example of insertion sort from real life. Have you noticed, how do tailors arrange customers
shirts in their wardrobe, according to size. So they insert a new shirt at the proper position, for that, they shift
existing shirts until they find the proper place.

If you consider wardrobe as an array and shirts as an element, you will find out that we need to shift existing
elements to find the right place for the new element. This is the core of the insertion sort algorithm, if you
understand these examples, even you can come up with a step by step coding algorithm to sort an array of an
integer using insertion sort in Java.

In this article, we will learn that by first understanding insertion sort with flowchart and by walking through an
example. After that writing, a Java method to do insertion sort will be very easy.

Btw, If you are a complete beginner into data structure and algorithm then I suggest you join a comprehensive
course like Data Structures and Algorithms: Deep Dive Using Java on Udemy, which will not only teach you
the Insertion sort algorithms but also other essential data structure and sorting algorithms. It's one of my favorite
course on this topic

How the Insertion Sort Algorithm works


If you know how to sort a hand of cards, you know how insertion sort works; but for many programmers, it's not
easy to translate real-world knowledge into a working code example.

This is where natural programming ability comes into play. A good programmer has the ability to code any
algorithm and convert a real-life example to an algorithm.

Now, how do you sort an array of an integer using this algorithm? You can say that we can treat this array as a
deck of cards, and we will use another array to pick and place an element from one place to another. Well, that
will work, but it's a waste of space (memory) because what you are doing is comparing and shifting, which can
also be done in place in the same array.

Here is the step by step guide to coding insertion sort algorithm in Java:

1) Consider the first element is sorted and it's on the proper place, that is index 0 for your array.

2) Now go to the second element (index 1 in the array), and compare it with what is in your hand (the part of the
array, which is already sorted). Which means you compare this element going backward towards index zero.

3) If the current number is smaller than the previous number (which is in the proper place), we need to put
our current number before that. How will we do that? Well for that we need to shift the existing number.

But what if there is another element that is greater than our current element? It means we need to continue
comparing until we found a proper place for our current number, which again means current number>
existing number or we are at the start of the list (index 0 in the array).

4) You need to repeat this process for all the numbers in the list. Once you finish that, you have a sorted list or
array.

In short, insertion sort is all about finding the proper place for the current number. Once you find the proper
place, you need to shift the existing element to make a place for this new number. If you want to learn more
about Insertion sort and other sorting algorithms, you can also see the course Algorithms and Data Structures -
Part 1 and 2 or a good book like Algorithms in Nutshell which is a fantastic course to learn important Computer
Science Algorithms.

A Visual Explanation of Insertion Sort Algorithm


It's said that "A picture is worth a thousand words", this is quite true in the case of understanding sorting
algorithm. Earlier we had seen how easy it was to understand QuickSort algorithm using a GIF image, and now
we will again learn how Insertion sort works by following this diagram, It becomes extremely easy to explain how
insertion sort works with this example.

Here we have an integer array of both positive and negative numbers in random order. Our task is to sort this
unsorted array using Insertion Sort in the ascending order, which means the smallest element should be at the start
of the array and the largest element must be at the end of the array.

To start working we assume that our first element is in the proper position (remember the first card in your hand)
and start with the second integer, which is -5. Now we compare it with 7, since - 5 is less than 7, we first move 7
in place of -5.

After this, we don't need to compare -5 with any other number because we have reached the left boundary so we
will put -5 at the current place. Now, we pick the third element which is 2. We compare 2 with 7 and found that 2
is also less than 7, which means 7 shifted in place of 2.

Next, we compare 2 with -5, now 2 is greater than -5 so we insert it at this place. After this, we pick the fourth
element which is 16. Since 16 is greater than 7, no need to shift anyone, 16 will remain in its place.

Now last element 4, it is less than 16 to 16 will move in place of 4, next we compare 4 with 7, again 4 is less than
so 7 will be shifted, after this we compare 4 with 2, wow it's greater than 2, so we have found a proper place for 4.
We insert 4 there. Now there is no more element to process an array, so our array is now sorted.

You can see that at the last step our array is sorted in increasing order, starting from - 5 and ending at 16.

By the way, algorithms can be better understood by looking at flowchart or a real example with numbers or by
joining a good online course like Visualizing Data Structures and Algorithms in Java, which is also a great
way to learn basic data structure and algorithms.

Insertion Sort in Java with Example


It's very easy to implement Insertion sort in Java. All you need to do is to iterate over the array and find the
proper position of each element, for that you need to shift element and you can do it by swapping. The logic of
sorting integer array using the insertion sort algorithm is inside method insertionSort(int[]).

In Java you can also sort any object e.g. String using this algorithm, all you need to do is to use a Comparable
interface because that will provide you mechanism to compare two objects. Now instead of using > (greater than)
or < (less than) operator, we need to use compareTo() method.

For this, we have decided to overload our insertionSort() method, where an overloaded version takes an Object
array instead of an int array. Both methods sort element using insertion sort logic.

By the way, in the real world, you don't need to reinvent the wheel, java.util.Arrays class provides several
utility methods to operate upon arrays and one of them is sort.

There is a couple of overloaded version of sort() method available to sort primitive and object arrays. This
method uses double-pivot QuickSort to sort the primitive array and MergeSort to sort object array.

Anyway, here is our complete code example to run the Insertion sort in Java. If you are using Eclipse IDE then
just copy-paste the code in the src folder of your Java project and Eclipse will create packages and source
files with the same name by itself. All you need to is that run it as a Java program.

import java.util.Arrays;

/**
* Java program to sort an array using Insertion sort algorithm.
* Insertion sort works great with already sorted, small arrays but
* not suitable for large array with random order.
*
* @author Javin Paul
*/
public class InsertionSort {

public static void main(String args[]) {

// getting unsorted integer array for sorting


int[] randomOrder = getRandomArray(9);
System.out.println("Random Integer array before Sorting : "
+ Arrays.toString(randomOrder));

// sorting array using insertion sort in Java


insertionSort(randomOrder);
System.out.println("Sorted array uisng insretion sort : "
+ Arrays.toString(randomOrder));

// one more example of sorting array using insertion sort


randomOrder = getRandomArray(7);
System.out.println("Before Sorting : " + Arrays.toString(randomOrder));
insertionSort(randomOrder);
System.out.println("After Sorting : " + Arrays.toString(randomOrder));

// Sorting String array using Insertion Sort in Java


String[] cities = {"London", "Paris", "Tokyo", "NewYork", "Chicago"};
System.out.println("String array before sorting : "
+ Arrays.toString(cities));
insertionSort(cities);

System.out.println("String array after sorting : "


+ Arrays.toString(cities));
}

public static int[] getRandomArray(int length) {


int[] numbers = new int[length];
for (int i = 0; i < length; i++) {
numbers[i] = (int) (Math.random() * 100);
}
return numbers;
}

/*
* Java implementation of insertion sort algorithm to sort
* an integer array.
*/
public static void insertionSort(int[] array) {
// insertion sort starts from second element
for (int i = 1; i < array.length; i++) {
int numberToInsert = array[i];
int compareIndex = i;
while (compareIndex > 0 && array[compareIndex - 1] > numberToInsert) {
array[compareIndex] = array[compareIndex - 1]; // shifting element
compareIndex--; // moving backwards, towards index 0
}
// compareIndex now denotes proper place for number to be sorted
array[compareIndex] = numberToInsert;
}
}

/*
* Method to Sort String array using insertion sort in Java.
* This can also sort any object array which implements
* Comparable interface.
*/
public static void insertionSort(Comparable[] objArray) {
// insertion sort starts from second element
for (int i = 1; i < objArray.length; i++) {
Comparable objectToSort = objArray[i];

int j = i;
while (j > 0 && objArray[j - 1].compareTo(objectToSort) > 1) {
objArray[j] = objArray[j - 1];
j--;
}
objArray[j] = objectToSort;
}
}

Output:
Random Integer array before Sorting : [74, 87, 27, 6, 25, 94, 53, 91, 15]
Sorted array uisng insretion sort : [6, 15, 25, 27, 53, 74, 87, 91, 94]
Before Sorting : [71, 5, 60, 19, 4, 78, 42]
After Sorting : [4, 5, 19, 42, 60, 71, 78]
String array before sorting : [London, Paris, Tokyo, NewYork, Chicago]
String array after sorting : [Chicago, London, NewYork, Paris, Tokyo]
Another useful thing to learn from this example is how to generate Random numbers in Java. You can see that our
getRandomArray(int length) method creates a random array of a given length.

This uses static utility method Math.random() which returns a double value between 0.0 to 0.1, if you need to
convert it to an integer, in the range of 0 to 99, you need to multiply it with 100. After that, you can cast it to int
to get rid of decimals.

That's all about the Insertion sort in Java. It's one of the really beautiful algorithms and works best for the
already sorted list. It has lots of practical uses but has limitations also. You should not use Insertion sort for
sorting a big list of numbers, as its best-case performance is in order of O(n), which can be very high for a list
of say 1 million integers.

To short those lists, you need sorting algorithms that have logarithmic complexity e.g. quicksort, mergesort, or
heapsort, which provides the best-case complexity of O(nLogn), because log reduces the power of 10^n into n
like 1 million will become 10^6 means 6.

In order to remember the Insertion sort algorithm, just remember how you sort your hand in poker or any card
game. If that is tough, just remember how you arrange your shirts in the wardrobe.

How to Reverse String in Java with or without StringBuffer Example


Reverse String in Java
There are many ways to reverse a given String in Java. For example, you can use rich Java API to quickly reverse
the contents of any String object. Java library provides StringBuffer and StringBuilder class with
the reverse() method which can be used to reverse String in Java. Since converting between String and
StringBuffer or StringBuilder is very easy it's the easiest way available to reverse String in Java. But,
in a coding interview, you may not be allowed to use the JDK API methods to solve this problem. That's why,
writing a Java program to reverse String in Java without StringBuffer is one of the popular Java String interview
questions, which requires you to reverse String by applying logic and by not using API methods.

Since reverse is a recursive job, you can use recursion as well as a loop to reverse String in Java. In this Java
tutorial, you will learn how to reverse String using StringBuffer, StringBuilder, and using a pure loop with
logic.
Btw, if you are preparing for coding interviews then a good knowledge of techniques like Recursion, Dynamic
Programming, Greedy Algorithms, and essential data structures like an array, string, linked list, binary tree, stack,
queue, etc are very important.

Algorithm to Reverse String in Java


Here are the algorithm and codes to reverse a given String in Java without using StringBuffer or any other API
methods. The method below shows you how to reverse the String, which you can further reuse to check if
the given String is Palindrome or not.

After initial input validation, we are just iterating through String, starting from end to start and generating a
reverse String.
Java Program to Reverse String in Java
Here is my complete code program to reverse any String in Java. In the main method, we have first used
StringBuffer and StringBuilder to reverse the contents of String and then we wrote our own logic to
reverse String.

This uses the toCharArray() method of String class which returns the character array of String. By looping
through the character array and appending it into an empty String we can get a reversed String in Java, as shown
in the following example.

You can also check How to reverse String with recursion in Java if you want to see the recursive code. let's see
the complete Java program for this beautiful Java programming exercise.

/**
*
* Java program to reverse String in Java.
* There are multiple ways to reverse
* String in Java, you can either take help of standard
* Java API StringBuffer to reverse String in Java.
* StringBuffer has a reverse() method which returns StringBuffer
* with reversed contents.
*
* On the other hand, you can also reverse it by applying your
* own logic, if asked to reverse String without
* using StringBuffer in Java.
*
* By the way you can also use StringBuilder to reverse
* String in Java. StringBuilder is non-thread-safe
* version of StringBuffer and provides similar API.
* You can use StringBuilder's reverse()
* method to reverse content and then convert it back to String
*
* @author http://java67.blogspot.com
*/
public class StringReverseExample {

public static void main(String args[]) {

//quick wasy to reverse String in Java - Use StringBuffer


String word = "HelloWorld";
String reverse = new StringBuffer(word).reverse().toString();
System.out.printf(" original String : %s ,
reversed String %s %n", word, reverse);

//another quick to reverse String in Java - use StringBuilder


word = "WakeUp";
reverse = new StringBuilder(word).reverse().toString();
System.out.printf(" original String : %s ,
reversed String %s %n", word, reverse);

// one way to reverse String without using


// StringBuffer or StringBuilder is writing
// own utility method
word = "Band";
reverse = reverse(word);
System.out.printf(" original String : %s ,
reversed String %s %n", word, reverse);
}

public static String reverse(String source){


if(source == null || source.isEmpty()){
return source;
}
String reverse = "";
for(int i = source.length() -1; i>=0; i--){
reverse = reverse + source.charAt(i);
}

return reverse;
}

Output:
original String: HelloWorld, reversed String dlroWolleH
original String: WakeUp, reversed String pUekaW
original String: Band, reversed String dnaB

That's all on How to reverse String in Java with and without StringBuffer and StringBuilder. Though being
a Java programmer I prefer to use a library and suggest anyone use StringBuffer or StringBuilder to
reverse String for any production use. Though it's also a good programming exercise and you should practice it
before going for any Java programming interview.

QuickSort Algorithm Example in Java using Recursion


The Quicksort algorithm is one of the very popular sorting algorithms in programming, often used to sort a large
array of numbers. Though there is numerous algorithm available to sort a list of objects, including integer, string,
and floating-point number, quicksort is best for general purpose. It's a divide and conquers algorithm, where we
divide the given array with respect to a particular element, known as 'pivot' such that the lower partition of the
array is less than the pivot and upper partition elements of the array are higher than the pivot.

The Quicksort is also one of the best examples of recursion, a key programming technique to solve Algorithmic
problems. This algorithm is naturally recursive because it sorts the large list by dividing it into smaller sub-list
and then applying the same algorithm to those.

The base case of recursion is when a list contains either one or zero elements, in that case, they are already sorted.
Quicksort is well ahead with primitive sorting algorithms like Insertion sort, selection sort, and Bubble sort. The
average time complexity of quicksort is O(N log N), while in the worst case its performance is similar to
bubble sort, I mean O(n^2).

Apparently, the worst case of quicksort is the best case of insertion sort, where they have to sort an already sorted
list. In this article, we will learn how to implement a quicksort algorithm in Java using recursion.

We will also learn how quicksort works, and how it sorts a large list of unsorted numbers. In the last section, we
will revisit some important things about quicksort.

How the QuickSort Algorithm Perform Sorting


An old saying is, a picture is worth more than a thousand words. This is completely true in the case of
understanding how the sorting algorithm works.

In the past, I have understood Insertion sort, Bubble sort, and Radix sort much better by following a diagram
rather than reading about it.

That's why I am sharing this diagram which explains how the quicksort algorithm works, how it sort a list of
integers. It's similar to a flowchart but doesn't use the notation flowchart uses, instead it practically shows how
sorting happens.

Once you go through this diagram, read the explanation, it will make more sense.
As I told before QuickSort is a recursive algorithm, it divides the big list into smaller list around pivot until those
lists are individually sorted. The first step of the Quicksort algorithm is to determine pivot, it's general practice to
choose the middle element of the array as a pivot, but you are free to choose any index.

Now you have two lists, the next step is to ensure that the left partition only contains numbers less than the pivot
and the right partition only contains numbers greater than the pivot.

We start pointer from left and right of the pivot, and as soon as the left pointer encounter 4, it stops because 4 is
greater than 3. Similarly, the right pointer stops at 3 because all numbers on the right side of the list are greater
than 3.

Now it's time to swap, so 3 takes place of 4 and vice-versa. Now, we move the pointer to one more step, since 2
> 3, the left pointer shifts but since 4 > 3, it stopped.

Since the left point is also past the right pointer it stopped. Now if we repeat this process one more time, the list
will be sorted. If you still don't get the algorithm then I suggest you join the Visualizing Data Structures and
Algorithms in Java course on Udemy. A special course that will teach you data structures and algorithms in Java
through animations and implementations.

The Concept of Pivot and Partition


Though we often select a middle element of the array as a pivot, there is no such rule and pivot can be an element
of the given array. You can even consider the first element as the pivot in every partition.

It's experienced that choice of pivot affects the distribution of the elements in partitioning and affects the
complexity of the quicksort algorithm.

As per the rule of partition, numbers in the lower partition should be less than the pivot and upper partition
numbers should be higher than the pivot. The running time of partition logic is linear.

The complexity of Quicksort Algorithm:

On average Quicksort Algorithm has the complexity of O(NlogN) and in the worst case, it has O(n²) when the
elements of the input array are already sorted in ascending or descending order.

The good thing about Quicksort is that it's an in-place algorithm, which means it does not take any additional
space, except those used by method stack.

By the way, there are some tricks to improve the performance of quicksort, even in the worst case. As
suggested in one of the best algorithm design book, The Algorithm Design Manual, from Steven Skiena, you
can apply the following the recommendation to improve your quicksort algorithm implementation.
1) Randomization
You can avoid the worst-case performance of O(n²) when sorting nearly-sorted data by random permutation of
keys. Though it incurs some cost of permutation still gives better performance than O(n²)

2) Leave small sub-arrays for Insertion sort


finish Quicksort recursion and switch to insertion sort when fewer than 20 elements:
There is a drawback of using recursion to implement quicksort algorithm, It will not scale because JVM has no
tail call optimization, it will simply grow the method call stack to something proportional to the array to sort, and
it will fail for the very large array.

Btw, if you have trouble understanding how we calculate the time and space complexity of an algorithm or
solution, I suggest you check out Algorithms and Data Structures - Part 1 and 2, a two-part series in
Pluralsight to learn how to calculate time complexity. It's an excellent course for beginners.

Java Program to Sort Integer Array using QuickSort Algorithm


Here is our recursive implementation of the QuickSort sorting algorithm. We have used it to sort an array of
randomly distributed integers. We have two sets of inputs, one which doesn't contain any repeated numbers and
the other which contains duplicates.

The Logic of quicksort is encapsulated in method recursiveQuickSort(int[] array, int


startIdx, int endIdx) and partition(int[] array, int left, int right), which
implements partitioning logic.

In order to hide implementation details, we have only exposed a convenient static utility method called
quickSort(int[] array), which takes an integer array and sorts that in-place.

package test;

import java.util.Arrays;

/**
* Java program to Sort integer array using QuickSort algorithm using recursion.
* Recursive QuickSort algorithm, partitioned list into two parts by a pivot,
* and then recursively sorts each list.
* @author Javin Paul
*/
public class QuickSort{

public static void main(String args[]) {

int[] input = { 23, 31, 1, 21, 36, 72};


System.out.println("Before sorting : " + Arrays.toString(input));
quickSort(input); // sort the integer array using quick sort algorithm
System.out.println("After sorting : " + Arrays.toString(input));

// input with duplicates


int[] withDuplicates = { 11, 14, 16, 12, 11, 15};
System.out.println("Before sorting : "
+ Arrays.toString(withDuplicates));
quickSort(withDuplicates); // sort the array using quick sort algorithm
System.out.println("After sorting : "
+ Arrays.toString(withDuplicates));
}

/**
* public method exposed to client, sorts given array using QuickSort
* Algorithm in Java
* @param array
*/
public static void quickSort(int[] array) {
recursiveQuickSort(array, 0, array.length - 1);
}

/**
* Recursive quicksort logic
*
* @param array input array
* @param startIdx start index of the array
* @param endIdx end index of the array
*/
public static void recursiveQuickSort(int[] array, int startIdx,
int endIdx) {

int idx = partition(array, startIdx, endIdx);

// Recursively call quicksort with left part of the partitioned array


if (startIdx < idx - 1) {
recursiveQuickSort(array, startIdx, idx - 1);
}

// Recursively call quick sort with right part of the partitioned array
if (endIdx > idx) {
recursiveQuickSort(array, idx, endIdx);
}
}

/**
* Divides array from pivot, left side contains elements less than
* Pivot while right side contains elements greater than pivot.
* @param array array to partitioned
* @param left lower bound of the array
* @param right upper bound of the array
* @return the partition index
*/
public static int partition(int[] array, int left, int right) {
int pivot = array[left]; // taking first element as pivot

while (left <= right) {


//searching number which is greater than pivot, bottom up
while (array[left] < pivot) {
left++;
}
//searching number which is less than pivot, top down
while (array[right] > pivot) {
right--;
}

// swap the values


if (left <= right) {
int tmp = array[left];
array[left] = array[right];
array[right] = tmp;

//increment left index and decrement right index


left++;
right--;
}
}
return left;
}
}

Output:
Before sorting : [23, 31, 1, 21, 36, 72]
After sorting : [1, 21, 23, 31, 36, 72]
Before sorting : [11, 14, 16, 12, 11, 15]
After sorting : [11, 11, 12, 14, 15, 16]

Things to know about QuickSort Algorithm in Java


As I said, QuickSort is one of the most popular sorting algorithms between programmers, maybe just next to
Bubble sort, which is ironically the worst algorithm to sort a large list of numbers. But one thing is common
between QuickSort and Bubble Sort, do you know what? In the worst case, both have the complexity of O(n^2).

1) QuickSort is a divide and conquer algorithm, which means it sort a large array of numbers by dividing them
into a smaller array and then individually sorting them (conquer).

2) Average case complexity of Quicksort is O(n log(n)) and the worst-case complexity of Quicksort
is O(n²).

3) Quicksort is a comparison sort and, inefficient implementations, it's not a stable sort, which means equal
numbers may not retain their original position after sorting.

4) Quicksort algorithm can be implemented in-place, which means no additional space will be required. This
makes it suitable to sort a large array of numbers.
5) The Arrays.sort() method in Java uses quicksort to sort an array of primitives like an array of integers or
float and uses Mergesort to sot objects like an array of String.

That's all about how to implement a QuickSort algorithm in Java. QuickSort is one of the fast and efficient
sorting algorithm, perfect for sorting large arrays, but some programmer finds it extremely hard to understand.
One reason for this could be that because quicksort is an in-place algorithm due to which programmers find it a
bit confusing, but it's very efficient. Otherwise, if you choose simplicity you can always implement it in other
ways.

How to Find Duplicate Characters on String - Java


Programming Problems
Hello guys, today's programming exercise is to write a program to find repeated characters in a String. For
example, if given input to your program is "Java", it should print all duplicates characters, i.e. characters appear
more than once in String and their count like a = 2 because of character 'a' has appeared twice in String
"Java". This is also a very popular coding question on the various level of Java interviews and written tests,
where you need to write code. On difficulty level, this question is at par with the prime numbers or Fibonacci
series, which are also very popular on junior level Java programming interviews and it's expected from every
programmer to know how to solve them.

I personally like this exercise because it gives beginners an opportunity to familiarize themselves with the concept
of Map data structure, which allows you to store mappings in the form of key and value.

Since Map and Hash table data structure is heavily used in any enterprise Java application, good knowledge of
this data structure is highly desirable among any level of Java programmers.

By the way, there are a couple of variants of this problem, which you may want to look before going for an
interview.

Sometimes an interviewer will ask you to read a file and print all duplicate characters and their count, core logic
will remain same, all you need to do is demonstrate how much you know about File IO in Java, like streaming file
if it's very large rather than reading the whole file in memory.

Java Program to find Repeated Characters of String


The standard way to solve this problem is to get the character array from String, iterate through that and build a
Map with character and their count. Then iterate through that Map and print characters which have appeared more
than once. So you actually need two loops to do the job, the first loop to build the map and second loop to print
characters and counts.

If you look at the below example, there is only one static method called printDuplicateCharacters(),
which does both this job. We first got the character array from String by calling toCharArray().

Next, we are using HashMap to store characters and their count. We use containsKey() method to check if
key, which is a character already exists or not if already exists we get the old count from HashMap by calling
get() method and store it back after incrementing it by 1.

Once we build our Map with each character and count, the next task is to loop through Map and check each entry,
if count, which is the value of Entry is greater than 1, then that character has occurred more than once. You can
now print duplicate characters or do whatever you want with them.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/**
* Java Program to find duplicate characters in String.
*
*
* @author http://java67.blogspot.com
*/
public class FindDuplicateCharacters{

public static void main(String args[]) {


printDuplicateCharacters("Programming");
printDuplicateCharacters("Combination");
printDuplicateCharacters("Java");
}

/*
* Find all duplicate characters in a String and print each of them.
*/
public static void printDuplicateCharacters(String word) {
char[] characters = word.toCharArray();

// build HashMap with character and number of times they appear in String
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
for (Character ch : characters) {
if (charMap.containsKey(ch)) {
charMap.put(ch, charMap.get(ch) + 1);
} else {
charMap.put(ch, 1);
}
}

// Iterate through HashMap to print all duplicate characters of String


Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();
System.out.printf("List of duplicate characters in String '%s' %n", word);
for (Map.Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
}
}
}

Output
List of duplicate characters in String 'Programming'
g : 2
r : 2
m : 2
List of duplicate characters in String 'Combination'
n : 2
o : 2
i : 2
List of duplicate characters in String 'Java'

That's all on how to find duplicate characters in a String. Next time if this question is asked to you in a
programming job interview, you can confidently write a solution and can explain them. Remember this question
is also asked to write a Java program to find repeated characters of a given String, so don't get confused yourself
in wording, the algorithm will remain the same.

How to swap two Integers without using temporary


variable in Java?
One of the oldest trick questions from a programming interview is, How do you swap two integers without using
temp variable? This was first asked to me on a C/C++ interview and then several times on various Java
interviews. The beauty of this question lies both on the trick to thinking about how you can swap two numbers
without the third variable, but also problems associated with each approach. If a programmer can think about
integer overflow and consider that in its solution then it creates a very good impression in the eye of interviewers.

Ok, so let's come to the point, suppose you have tow integers i = 10 and j = 20, how will you swap them
without using any variable so that j = 10 and i = 20? Though this is journal problem and solution work more
or less in every other programming language, you need to do this using Java programming constructs.

You can swap numbers by performing some mathematical operations like addition and subtraction and
multiplication and division, but they face the problem of integer overflow.
There is a neat trick of swapping number using XOR bitwise operator which proves to be the ultimate solution.
We will explore and understand each of these three solutions in detail here,

and if you are hungry for more programming questions and solutions, you can always take a look at Grokking
the Coding Interview: Patterns for Coding Questions, one of the best course to prepare for programming job
interviews.

2 Ways to swap two integers without using a temp variable in Java


Now that you are familiar with the problem let's talk about the solution. There are two main ways to solve this
problem one using arithmetic operators and others using a bitwise operator. There are some loopholes in the first
solution like overflow which can also get you some brownie points if you can bring them during interviews.

Solution 1 - Using Addition and Subtraction


You can use + and - operator in Java to swap two integers as shown below :

a = a + b;
b = a - b; // actually (a + b) - (b), so now b is equal to a
a = a - b; // (a + b) -(a), now a is equal to b

You can see that its a really nice trick and the first time it took some time to think about this approach. I was
really happy to even think about this solution because its neat, but happiness was short-lived because the
interviewer said that it will not work in all conditions.

He said that integer will overflow if the addition is more than the maximum value of int primitive as defined by
Integer.MAX_VALUE and if subtraction is less than the minimum value, I mean Integer.MIN_VALUE.

It confused me and I conceded only to find that the code is absolutely fine and work perfectly in Java because
overflows are clearly defined. And, Yes, the same solution will not work in C or C++ but it will work absolutely
fine in Java.

Don't believe me? here is the proof :

a = Integer.MAX_VALUE;
b = 10;

System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);

a = (a + b) - (b = a);
System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);

Output :
Before swap 'a': 2147483647, 'b': 10
After swapping, 'a': 10, 'b': 2147483647

Here the addition of two numbers will overflow, Integer.MAX_VALUE + 10 = -2147483639, but we
are also doing subtraction, which will compensate this value because b is now Integer.MAX_VALUE and -
2147483639 - 2147483647 will again overflow to give you 10 as output.

This covers all basic including bitwise operators which we will see in the next section and it is also the most up-
to-date course. You can buy in just $9.99 on crazy Udemy sales which happen every now and then.

Btw, it's a lot easier to solve this problem and swap variables in Python, so its highly unlikely that you will get
this problem during a Python interview :-)

Solution 2 - Using XOR trick


The second solution to swap two integer numbers in Java without using the temp variable is widely recognized as
the best solution, as it will also work in a language that doesn't handle integer overflows like Java, for
example, C and C++. Java provides several bitwise and bitshift operators, one of them is XOR which is denoted
by ^.

If you remember the XOR truth table then you know that A XOR B will return 1 if A and B are different and 0
if A and B are the same. This property gives birth to following code, popularly know as XOR trick:

x = x ^ y;
y = x ^ y; // now y = x
x = x ^ y; // now x = y

Here is an example of swapping two numbers using XOR bitwise operator in Java, you can see that values of X
and Y are swapped after the third operation.
And, if you want to learn more about Bitwise operator in Java and Programming in general, I highly recommend
you read the Hackers Delight by Henry S. Warren book, its the bible to learn about bitwise and bitshift operation
and reverted by expert programmers.

Program to Swap Two Integers without a temporary variable in Java


In this Java program, I will show you a couple of ways to swap two integers without using any temporary or third
variable, and what problems come with each approach and which one will work in all conditions.

Actually, the two popular solution works perfectly fine in Java but candidates, especially those coming from C
and C++ background often think that first solution is broken and will fail on integer boundaries, but that's not true.

Integer overflows are clearly defined in Java, like Integer.MAX_VALUE + 1 will result in
Integer.MIN_VALUE, which means if you do both addition and subtraction in with the same set of numbers,
your result will be fine, as seen in the above example.

/**
* Java program to swap two integers without using temp variable
*
* @author java67
*/
public class Problem {

public static void main(String args[]) {


int a = 10;
int b = 20;

// one way using arithmetic operator e.g. + or -


// won't work if sum overflows
System.out.println("One way to swap two numbers without temp variable");
System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);
a = a + b;
b = a - b; // actually (a + b) - (b), so now b is equal to a
a = a - b; // (a + b) -(a), now a is equal to b

System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);

// another example
a = Integer.MIN_VALUE;
b = Integer.MAX_VALUE;

System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);

a = (a + b) - (b = a);

System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);

// Another way to swap integers without using temp variable is


// by using XOR bitwise operator
// Known as XOR trick
System.out.println("Swap two integers without third variable
using XOR bitwise Operator");

int x = 30;
int y = 60;

System.out.printf("Before swap 'x': %d, 'y': %d %n", x, y);


x = x ^ y;
y = x ^ y;
x = x ^ y;

System.out.printf("After swapping, 'x': %d, 'y': %d %n", x, y);


}

Output
One way to swap two numbers without temp variable
Before swap 'a': 10, 'b': 20
After swapping, 'a': 20, 'b': 10
Before swap 'a': -2147483648, 'b': 2147483647
After swapping, 'a': 2147483647, 'b': -2147483648
Swap two integers without third variable using XOR bitwise Operator
Before swap 'x': 30, 'y': 60
After swapping, 'x': 60, 'y': 30

That's all about how to swap two integers without using a temporary variable in Java. Unlike popular belief
that the first solution will not work on integer boundaries i.e. around maximum and minimum values, which is
also true for languages like C and C++, it works perfectly fine in Java. Why? because overflow is clearly defined
and addition and subtraction together negate the effect of overflow.

There is no doubt about the second solution as it is the best solution and not subject to any sign or overflow
problem. It is also believed to be the fastest way to swap two numbers without using temp variable in Java.

Factorial in Java using Recursion and Loop


Problem : Write a program to calculate factorial of a given number in Java, using both recursion and iteration.

Solution : If you come from Maths background then you know that factorial of a number is
number*(factorial of number -1). You will use this formula to calculate factorial in this Java
tutorial. Since factorial is a naturally recursive operation, it make sense to use recursion to solve this problem but
its not always the best way. Iteration provides a more robust way, but don't worry you will learn how to calculate
factorial with and without recursion in Java. By the way, factorial of numbers grows very quickly and even the
largest integral data type in Java, long is not able to hold factorial of anything or above 50. In such cases you can
use BigInteger, which has theoretically no limit and can be used to represent very large integral numbers.

Solution 1 : Factorial using recursion


In order to create a recursive solution you need a base case where program terminates and in this problem base
case is factorial of 1, which is 1. So if given number is greater than 1, we keep applying factorial formula and
recursive call this method with n - 1 as shown below :

public static long factorial(int number){


//base case - factorial of 0 or 1 is 1
if(number <=1){
return 1;
}
return number*factorial(number - 1);
}
Once input become 1 the method stopped recursive call and return 1. From there onward stack started to roll
down and finally factorial of number is calculated.
Solution 2 : Factorial without Recursion

As I said instead of using recursion and calling factorial method again you can also use for loop to calculate
factorial because !n = n*(n-1)*(n-2).....*1 , which can easily be implemented using loop as shown
below :

public static long factorial(long input){


long factorial = 1L;
for(long i= input; i > 0; i--){
factorial = factorial * i;
}

return factorial;
}
You can see that we start with the number and multiply it with the factorial which is initialized with 1 then we
reduce the number by 1 until number becomes 1, which is nothing but n*(n-1)*(n-2).....*1.

Java Program to calculate Factorial with and without Recursion


Here is our complete solution of this problem. You can see that I have created two factorial() method, one
accept int and return long e.g. long factorial(int number), while other accept a long and return a long
factorial i.e. long factorial(long number). Since their parameter type is different they are two different
method also known as overloaded methods. First method uses recursion to calculate factorial while second
method uses iteration to calculate factorial.
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
* Java Program to calculate factorial using iteration and recursion
*
* @author WINDOWS 8
*
*/
public class FactorialTest {

public static void main(String args[]) {

System.out.println("factorial of 1 using recursion : " + factorial(1));


System.out.println("factorial of 1 using iteration : " + factorial(1L));

System.out.println("factorial of 5 using recursion : " + factorial(5));


System.out.println("factorial of 5 using loop : " + factorial(5L));

System.out.println("factorial of 7 using recursive algorithm : " +


factorial(7));
System.out.println("factorial of 7 using iterative algorithm : " +
factorial(7L));

/**
* Java method to calculate factorial of given integer using recursion.
* @param number
* @return factorial of number
*/
public static long factorial(int number){
//base case - factorial of 0 or 1 is 1
if(number <=1){
return 1;
}
return number*factorial(number - 1);
}

/**
* Java method to calculate factorial of given number using iteration
* @param input
* @return factorial of input
*/
public static long factorial(long input){
long factorial = 1L;
for(long i= input; i > 0; i--){
factorial = factorial * i;
}
return factorial;
}
}

Output :
factorial of 1 using recursion : 1
factorial of 1 using iteration : 1
factorial of 5 using recursion : 120
factorial of 5 using loop : 120
factorial of 7 using recursive algorithm : 5040
factorial of 7 using iterative algorithm : 5040

That's all about how to calculate factorial of a number in Java using both recursion and iteration. This
problem is often used to teach programming, particularly recursion in school and colleges and its good one as
well. Just remember that even though recursive solution are small and clear they are prone to throw
StackOverFlowException, hence not suitable for production code. Iteration or use of for loop results in
more robust solution.
How to find largest and smallest number from integer
array - Java Solution
Hello guys, if you have gone through any coding interview or have done some professional Software development
then you know that a good understanding of array data structure is crucial for any software developer but it
doesn't come for free, you need to spend time and effort. The best way to develop this understanding by solving
coding problems and there are lots of programming exercises beginners can do. One of them is writing a program
to find the smallest and largest number in an integer array. Java programmers are no different than others, so they
can do this program in Java, not just to understand array but also different relational operators available in Java.

In this program, you need to write a method, yes we call the function a method in Java, which will accept an
integer array and then print the largest and smallest number from that array. Use of any third-party library or API
method is not allowed, which means you need to do this exercise by using essential tools of Java programming
language, which includes operators, control statements, keyword, and some classes from java.lang package.

This problem is also known as finding maximum and minimum numbers in an array, and the technique
mentioned here can be used in any other programming language as well. As a bonus point, you can also write
JUnit test cases to test your method, I have not done so and relied on simple main method to test my code to show
the output and keep it short, essential for any example or demo.

Btw, if you preparing for a programming job interview, then let me repeat that a good knowledge of essential data
structures like an array, linked list, binary tree, the hash table goes a long way in doing well on the interview. You
should spend some time learning those and filling gaps in your understanding.

Java Program to find the smallest and largest number in


an integer array

Here is a full code example of a Java program to find the smallest and largest number from an integer array. You
can create a Java source file with the name MaximumMinimumArrayDemo.java and copy code there to
compile and execute it in your favorite IDE. If you don't have an IDE setup, you can also compile and run this
program by following steps I have shown on HelloWorld in Java.

If you look at the code here, we have created a method called the largestAndSmallest(int[]
numbers) to print the largest and smallest number from int array passed to the program. We have used two
variables largest and smallest, to store the maximum and minimum values from the array. Initially, the largest is
initialized with Integer.MIN_VALUE and smallest is initialized with Integer.MAX_VALUE.
In each iteration of the loop, we compare the current number with the largest and smallest and update them
accordingly. Since if a number is larger than largest, it can't be smaller than smallest, which means you don't need
to check if the first condition is true, that's why we have used if-else code block, where else part will only
execute if the first condition is not true.

Here is another logical diagram or flow chart to find the largest element from an array in Java, here instead of
assigning the variable with Integer.MAX_VALUE, we have assigned the first element from the array.

Since array doesn't override the toString method in Java, we have used Arrays.toString() to print the
contents of an array. Remember, this function is outside of core logic, so it's ok to use it. Since this is a static
method, we can directly call this from the main method in Java, and so does our test code.

We pass the random array to this method and see if the largest and smallest number returned by the method is
correct or not. For automated testing, a Unit test is better, but for a demonstration, you can use the main method.

Btw, if you preparing for a programming job interview, then don't forget to check the Cracking the Coding
Interview book. It contains 150 Programming Questions and Solutions, which is more than enough for many
coding interviews.

Java Program to find the largest and smallest element in an array:


import java.util.Arrays;
/**
* Java program to find largest and smallest number from an array in Java.
* You cannot use any library method both from Java and third-party library.
*
* @author http://java67.blogspot.com
*/
public class MaximumMinimumArrayDemo{

public static void main(String args[]) {


largestAndSmallest(new int[]{-20, 34, 21, -87, 92,
Integer.MAX_VALUE});
largestAndSmallest(new int[]{10, Integer.MIN_VALUE, -2});
largestAndSmallest(new int[]{Integer.MAX_VALUE, 40,
Integer.MAX_VALUE});
largestAndSmallest(new int[]{1, -1, 0});
}

public static void largestAndSmallest(int[] numbers) {


int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
for (int number : numbers) {
if (number > largest) {
largest = number;
} else if (number < smallest) {
smallest = number;
}
}

System.out.println("Given integer array : " + Arrays.toString(numbers));


System.out.println("Largest number in array is : " + largest);
System.out.println("Smallest number in array is : " + smallest);
}
}
Output:
Given integer array : [-20, 34, 21, -87, 92, 2147483647]
Largest number in array is : 2147483647
Smallest number in array is : -87
Given integer array : [10, -2147483648, -2]
Largest number in array is : 10
Smallest number in array is : -2147483648
Given integer array : [2147483647, 40, 2147483647]
Largest number in array is : 2147483647
Smallest number in array is : 40
Given integer array : [1, -1, 0]
Largest number in array is : 1
Smallest number in array is : -1

Java String Exercises: Find first non repeating character


in a string

Write a Java program to find first non repeating character in a string.

Pictorial Presentation:

Sample Solution:

Java Code:
import java.util.*;
public class Main {
public static void main(String[] args) {
String str1 = "gibblegabbler";
System.out.println("The given string is: " + str1);
for (int i = 0; i < str1.length(); i++) {
boolean unique = true;
for (int j = 0; j < str1.length(); j++) {
if (i != j && str1.charAt(i) == str1.charAt(j)) {
unique = false;
break;
}
}
if (unique) {
System.out.println("The first non repeated character in String is: " +
str1.charAt(i));
break;
}
}
}
}

Sample Output:

The given string is: gibblegabbler


The first non repeated character in String is: i

Java String Exercises: Print after removing duplicates


from a given string
Write a Java program to print after removing duplicates from a given string.

Pictorial Presentation:
Sample Solution:

Java Code:

import java.util.*;
public class Main {
public static void main(String[] args) {
String str1 = "w3resource";
System.out.println("The given string is: " + str1);
System.out.println("After removing duplicates characters the new string
is: " + removeDuplicateChars(str1));
}
private static String removeDuplicateChars(String sourceStr) {
char[] arr1 = sourceStr.toCharArray();
String targetStr = "";
for (char value: arr1) {
if (targetStr.indexOf(value) == -1) {
targetStr += value;
}
}
return targetStr;
}
}

Sample Output:

The given string is: w3resource


After removing duplicates characters the new string is: w3resouc

How to Reverse a String in place in Java - Example


It's possible to reverse a String in place by using a StringBuilder. Since String is Immutable in Java, it's not
possible to reverse the same String, but you can minimize the number of intermediate String objects by using
StringBuilder or StringBuffer, which are mutable. The algorithm to reverse the String in place is similar to the
algorithm we have used earlier to reverse an array in place. You need to traverse the String from one end,
swapping characters at another end until you reach the middle of the String. At the point characters in your String
is reversed. This algorithm only requires one extra character of memory to facilitate the swapping of characters.
The time complexity of this algorithm is O(n/2) i.e. O(n) where n is the length of String.

Ideally, whenever you need to reverse a String in your application, you should be using the reverse() method of
StringBuilder. This method reverses the character sequence of the String in place. It also handles the
surrogate pairs correctly. If there are any surrogate pairs included in the sequence, these are treated as single
characters for the reverse operation.

Thus, the order of the high-low surrogates is never reversed. Note that the reverse operation may result in
producing surrogate pairs that were unpaired low-surrogates and high-surrogates before the operation. For
example, reversing "\uDC00\uD800" produces "\uD800\uDC00" which is a valid surrogate pair.
Java Program to reverse String in place
Here is our sample Java program to solve this problem of reversing String in place i.e. without using additional
memory, barring one or two variables to keep track of positions. In this example, we have reversed String using
an iterative algorithm. It first converts String to StringBuilder, so that we can mutate the contents without creating
temporary String objects. Then, it goes through StringBuilder and swap characters from both ends until it reaches
the midpoint. At that point, String is reversed, without any additional memory i.e. in place.

/*
* Java Program to replace a String in place.
* Since String is Immutable in Java, you cannot reverse
* the same String, but a new String is get created.
* This program reverse a string in place using StringBuilder
*/
public class Main {

public static void main(String args[]) {

String number = "1234";


System.out.println("original String: " + number);
String reversed = inPlaceReverse(number);
System.out.println("reversed String: " + reversed);
}

/*
* Java method to replace a String in place
*/
public static String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final int otherEnd = length - i - 1;
builder.setCharAt(i, builder.charAt(otherEnd)); // swap
builder.setCharAt(otherEnd, current);
}
return builder.toString();
}
}
Output
original String: 1234
reversed String: 4321

You can see, we are not creating new String objects, instead just swapping characters in StringBuilder. A
common mistake many Java programmer makes while using this algorithm is to traverse the whole String, rather
than stopping midway.

It's the same mistake, we have talked about while reversing ArrayList in place. If you traverse the whole String,
you switch each character twice, and they will return to their original position, leaving String same an original.
Here is a nice diagram to explain this logic of reversing String in place, you can see how swapping of characters
happens at each pass in our loop:

That's all about how to reverse a String in place in Java. You can use the same algorithm to reverse any array
e.g. int or String array in Java as well. After all, String is also backed by a character array in Java. For further
preparation, you can also try to reverse a singly linked list in Java without recursion. It's a little bit tricky but if
you apply logic, it can be done. I am anyway, explain that in coming articles.

3 Ways to Find Duplicate Elements in an Array - Java


There are multiple ways to find duplicate elements in an array in Java and we will see three of them in this
program. The solution and logic shown in this article are generic and apply to an array of any type e.g. String
array or integer array or array of any object. One of the most common ways to find duplicates is by using the
brute force method, which compares each element of the array to every other element. This solution has the time
complexity of O(n^2) and only exists for academic purposes. You shouldn't be using this solution in the real
world.

The standard way to find duplicate elements from an array is by using the HashSet data structure. If you
remember, Set abstract data type doesn't allow duplicates. You can take advantage of this property to filter
duplicate elements.

This solution has a time complexity of O(n), as you only need to iterate over array once, but also has a space
complexity of O(n) as you need to store unique elements in the array.

Our third solution to find duplicate elements in an array is actually similar to our second solution but instead of
using a Set data structure, we will use the hash table data structure. This is a pretty good solution because you can
extend it to the found count of duplicates as well. In this solution, we iterate over the array and build the map
which stores array elements and their count.
Once the table is built, you can iterate over a hash table and print out all the elements, who have a count greater
than one, those are your duplicates.

How to find duplicates in Java array?


In the first paragraph, I have given you a brief overview of three ways to find duplicate elements from Java array.
Now, let's understand the logic behind each of those solutions in little more detail.

Solution 1:
Our first solution is very simple. All we are doing here is to loop over an array and comparing each element to
every other element. For doing this, we are using two loops, inner loop, and outer loop. We are also making sure
that we are ignoring comparing of elements to itself by checking for i != j before printing duplicates. Since we are
comparing every element to every other element, this solution has quadratic time complexity i.e. O(n^2). This
solution has the worst complexity in all three solutions.

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


for (int j = i + 1 ; j < names.length; j++) {
if (names[i].equals(names[j])) {
// got the duplicate element
}
}
}

Solution 2:
The second solution is even simpler than this. All you need to know is that Set doesn't allow duplicates in Java.
Which means if you have added an element into Set and trying to insert duplicate element again, it will not be
allowed. In Java, you can use the HashSet class to solve this problem. Just loop over array elements, insert them
into HashSet using add() method, and check the return value.

If add() returns false it means that element is not allowed in the Set and that is your duplicate. Here is the code
sample to do this :
for (String name : names) {
if (set.add(name) == false) {
// your duplicate element
}
}

The complexity of this solution is O(n) because you are only going through the array one time, but it also has a
space complexity of O(n) because of the HashSet data structure, which contains your unique elements. So if an
array contains 1 million elements, in the worst case you would need a HashSet to store those 1 million elements.

Solution 3 :
Our third solution takes advantage of another useful data structure, hash table. All you need to do is loop through
the array using enhanced for loop and insert each element and its count into hash table. You can use HashMap
class of JDK to solve this problem. It is the general purpose hash table implementation in Java. In order to build
table, you check if hash table contains the elements or not, if it is then increment the count otherwise insert
element with count 1. Once you have this table ready, you can iterate over hashtable and print all those keys
which has values greater than one. These are your duplicate elements. This is in fact a very good solution because
you can extend it to found count of duplicates as well. If you remember, I have used this approach to find
duplicate characters in String earlier. Here is how you code will look like :
// build hash table with count
for (String name : names) {
Integer count = nameAndCount.get(name);
if (count == null) {
nameAndCount.put(name, 1);
} else {
nameAndCount.put(name, ++count);
}
}

// Print duplicate elements from array in Java


Set<Entry<String, Integer>> entrySet = nameAndCount.entrySet();
for (Entry<String, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
System.out.printf("duplicate element '%s' and count '%d' :",
entry.getKey(), entry.getValue());
}
}
Time complexity of this solution is O(2n) because we are iterating over array twice and space complexity is
same as previous solution O(n). In worst case you would need a hash table with size of array itself.

Java Program to find duplicate elements in array


Here is our three solutions packed into a Java program to find duplicate elements in array. You can run this
example from command line or Eclipse IDE, whatever suits you. Just make sure that name of your Java source
file should be same as your public class e.g. "DuplicatesInArray". I have left bit of exercise for you, of
course if you would like to do. Can you refactor this code into methods, you can do that easily by using extract
method feature of IDE like Eclipse and Netbans and write unit test to check the logic of each approach. This
would give you some practice in refactoring code and writing JUnit tests, two important attributes of a
professional programmer.

package dto;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
* Java Program to find duplicate elements in an array. There are two straight
* forward solution of this problem first, brute force way and second by using
* HashSet data structure. A third solution, similar to second one is by using
* hash table data structure e.g. HashMap to store count of each element and
* print element with count 1.
*
* @author java67
*/

public class DuplicatesInArray{

public static void main(String args[]) {

String[] names = { "Java", "JavaScript", "Python", "C", "Ruby", "Java" };

// First solution : finding duplicates using brute force method


System.out.println("Finding duplicate elements in array using brute force method");
for (int i = 0; i < names.length; i++) {
for (int j = i + 1; j < names.length; j++) {
if (names[i].equals(names[j]) ) {
// got the duplicate element
}
}
}

// Second solution : use HashSet data structure to find duplicates


System.out.println("Duplicate elements from array using HashSet data structure");
Set<String> store = new HashSet<>();

for (String name : names) {


if (store.add(name) == false) {
System.out.println("found a duplicate element in array : "
+ name);
}
}

// Third solution : using Hash table data structure to find duplicates


System.out.println("Duplicate elements from array using hash table");
Map<String, Integer> nameAndCount = new HashMap<>();

// build hash table with count


for (String name : names) {
Integer count = nameAndCount.get(name);
if (count == null) {
nameAndCount.put(name, 1);
} else {
nameAndCount.put(name, ++count);
}
}

// Print duplicate elements from array in Java


Set<Entry<String, Integer>> entrySet = nameAndCount.entrySet();
for (Entry<String, Integer> entry : entrySet) {

if (entry.getValue() > 1) {
System.out.println("Duplicate element from array : "
+ entry.getKey());
}
}
}
}
Output :
Finding duplicate elements in array using brute force method
Duplicate elements from array using HashSet data structure
found a duplicate element in array : Java
Duplicate elements from array using hash table
Duplicate element from array : Java
From the output, you can see that the only duplicate element from our String array, which is "Java" has been
found by all of our three solutions.

That's all about how to find duplicate elements in an array in Java. In this tutorial, you have learned three ways
to solve this problem. The brute force way require you to compare each element from array to another, hence has
quadratic time complexity. You can optimize performance by using HashSet data structure, which doesn't allow
duplicates. So a duplicate element is the one for which add() method of HashSet return false. Our third solution
uses hash table data structure to make a table of elements and their count. Once you build that table, iterate over it
and print elements whose count is greater than one. This is a very good coding problem and frequently asked in
Java Interview. It also shows how use of a right data structure can improve performance of algorithm
significantly.

How to reverse an ArrayList in place in Java - Coding Interview Questions


You can reverse an ArrayList in place in Java by using the same algorithm we have used to reverse an array in
place in Java. If you have already solved that problem then It's a no-brainer because ArrayList is nothing but a
dynamic array, which can resize itself. All elements of an array are stored in the internal array itself. By the way,
if you need to reverse an ArrayList then you should be using the Collections.reverse() method provided
by the Java Collection framework. It's a generic method, so you can not only reverse an ArrayList but also
Vector, LinkedList, CopyOnWriteArrayList, or any other List implementation.

Though, worth noting is that this method internally uses a ListIterator for reversing the list, which might
not be as efficient as our algorithm.

If this question is asked in an interview, then you can also use recursion to reverse the ArrayList, as shown in this
article. The interviewer often tests the candidate with a recursive algorithm just to check if they understand
recursion or not.

Also, basic knowledge of essential data structure is also very important and that's why I suggest all Java
programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms:
Deep Dive Using Java on Udemy to fill the gaps in your understanding.
How to reverse an ArrayList in place in Java
Here is code to reverse an ArrayList of String in place. The algorithm is generic, so you can also use it to reverse
an ArrayList of Integer, Double, or any other object. If you look carefully, we are just iterating over the array and
swapping elements from the opposite end until we reach the middle of the list. At this point, our list is completely
reversed. This is the same algorithm we have used to reverse an array earlier.

// let's now reverse the list in place in Java


int size = listOfFood.size();
for (int i = 0; i < size / 2; i++) {
final String food = listOfFood.get(i);
listOfFood.set(i, listOfFood.get(size - i - 1)); // swap
listOfFood.set(size - i - 1, food); // swap
}

Though a couple of things, you need to keep in mind. Since we are using the set() method, you cannot pass an
unmodifiable or read-only ArrayList to this method. Using this algorithm with read-only ArrayList will throw
java.lang.UnSupportedOperationException.

The time complexity of this algorithm is O(n/2) i.e. O(n) where n is the size of ArrayList, and space
complexity is O(1) because we don't need additional list or space required by the recursive algorithm to reverse a
list in Java.

One more thing which you should keep in mind this algorithm should only be used with List which supports
RandomAccess e.g. ArrayList and Vector. Though you can reverse the LinkedList using this algorithm, it
will be of order O(n^2) because the linked list doesn't support index-based access and get() method traverse
the linked list to retrieve the desired element.

Since traversal in a linked list is O(n), the time complexity of algorithm rises to O(n^2) for reversing linked list
in place using this algorithm.

And, if you find Educative platform and their Grokking courses like Grokking the System Design Interview,
Grokking the Object-Oriented Programming interview then consider getting Educative Subscription which
provides access to their 100+ courses in just $18 per month. It's very cost-effective and great for preparing for
coding interviews.

Java Program to reverse an ArrayList in place


Here is our sample Java program to reverse an ArrayList of String in place. The algorithm is generic, so you can
also use it to reverse an ArrayList of Integer, Double, or any other object.

import java.util.ArrayList;
import java.util.List;
/*
* Java Program to reverse an ArrayList in place.
* When you reverse ArrayList in place, you are not
* allowed to use additional buffer e.g. an array
* or any collection.
*/
public class ReverseArrayListInPlace {

public static void main(String args[]) {

// Let's create a list of foods which helps


// to lose weight, one of the prime concern programmers
List<String> listOfFood = new ArrayList<>();
listOfFood.add("Beans");
listOfFood.add("Soup");
listOfFood.add("Dark Chocolate");
listOfFood.add("Yogurt");
listOfFood.add("Sausage");
listOfFood.add("Pure Vegetables");
listOfFood.add("Nuts");

System.out.println("Original ArrayList: " + listOfFood);

// let's now reverse the list in place in Java


int size = listOfFood.size();
for (int i = 0; i < size / 2; i++) {
final String food = listOfFood.get(i);
listOfFood.set(i, listOfFood.get(size - i - 1)); // swap
listOfFood.set(size - i - 1, food); // swap
}

System.out.println("Reversed ArrayList: " + listOfFood);


}

}
Output:
Original ArrayList: [Beans, Soup, Dark Chocolate, Yogurt, Sausage,
Pure Vegetables, Nuts]
Reversed ArrayList: [Nuts, Pure Vegetables, Sausage, Yogurt, Dark Chocolate,
Soup, Beans]

That's all about how to reverse an ArrayList in place in Java. Just keep in mind that you can use reverse
ArrayList of any object e.g. String, Integer, Float, or Double. You can also use this algorithm to
reverse Vector or any other List which supports index-based access.

One more requirement of this algorithm is that List should not be unmodifiable i.e. set() method should not
throw UnSupportedOperationException. Don't use this algorithm to reverse the linked list in Java
because time complexity would be O(n^2), you can see the following courses for more details on calculating
time and space complexity.

How to print Floyd's triangle in Java - Example Tutorial


In the last article, I have taught you how to print Pascal's triangle and in today's article I'll teach you how to print
Floyd's triangle in Java program. Floyd's triangle is easier to print than Pascal's triangle because you don't need
to take care of formatting the numbers as Floyd's triangle is a right angle triangle. It is named after American
computer scientist Robert Floyd, who has also contributed Floyd–Warshall algorithm, which efficiently finds all
shortest paths in a graph and Floyd's cycle-finding algorithm for detecting cycles in a sequence. If you remember,
we use this algorithm to find the cycles in linked list. Coming back to Floyd's triangle, it is a right angle triangle
which consists natural numbers starting from 1 in the first row. It then goes on with two numbers in second row, 3
numbers in 3rd row and so on. Along with other pattern based exercises and Pascal's triangle, Floyd's triangle is
also a good programming exercise and often used in programming and training courses to teach how to program
to beginners. It's one of the easier program but help you to build code sense and how to use basic programming
constructs e.g. loop, operators and functions.

Floyd's triangle questions is also asked on computer programming practical exams as, Can you write a Java
program to print Floyd's triangle of 5 rows as shown below:
1
23
456
7 8 9 10
11 12 13 14 15

Sometimes with additional constraints e.g. print Floyd's triangle up-to 5 rows, 10 rows or up to a given number of
rows entered by user. We'll implement the last part i.e. our Floyd's triangle will have as many rows as user wants.

Java Program to Print Floyd's triangle


Here is our sample Java program to print Floyd's triangle upto a given number of rows, which is entered by user.
We have used the Scanner class to read user input from command prompt, if you are not familiar with how to read
user input in Java see here. Scanner class has several benefits e.g. you don't need to read String and parse String
into integer, you can directly read integer using nextInt() method.

Once you have number of rows with you, it's very easy to print the Floyd's triangle. You can see we are printing a
two dimensional structure, a table, so we need two loop. First loop will print number of rows and the second loop,
the inner one will print numbers in each row. If you look closely, numbers in row is in increasing order and
doesn't reset between rows. So you just need to keep an integer number outside of loop and keep increasing it on
inner loop.

Like the pyramid pattern problem, we need to use both print() and println() method from System.out to
print numbers in same row and then switching to next row.

Btw, Rober Floyd's has contributed a lot in the field of computer science and some of his more important work
e.g. Floyd–Warshall algorithm to efficiently finds all shortest paths in a graph and Floyd's cycle-finding
algorithm for detecting cycles in a sequence are often taught in data structure and algorithm classes.

You can read a good algorithm book e.g. Introduction to Algorithms by Thomas Cormen to read more about
Floyd's shortest path algorithm and cycle detection algorithm.

Printing Floyd's triangle in Java

import java.util.Scanner;

/*
* Java Program to print Floyd's triangle as shown below:
* 1
* 2 3
* 4 5 6
* 7 8 9 10
* 11 12 12 14 15
*/

public class FloydTriangleInJava {

public static void main(String[] args) {

System.out.println("Welcome to Java program to print Floyd's triangle");


System.out.println("Please enter the number of rows of "
+ "Floyd's triangle you want to print");
Scanner scnr = new Scanner(System.in);
int rows = scnr.nextInt();

printFloydTriangle(rows);

scnr.close();
}
/*
* Java method to print Floyd's triangle upto given
* number of rows.
*/
public static void printFloydTriangle(int numberOfRows) {
int number = 1;
for (int row = 1; row <= numberOfRows; row++) {
for (int column = 1; column <= row; column++) {
System.out.print(number + " ");
number++;
}
System.out.println();
}
}

}
Output
Welcome to Java program to print Floyd's triangle
Please enter the number of rows of Floyd's triangle you want to print
5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Welcome to Java program to print Floyd's triangle


Please enter the number of rows of Floyd's triangle you want to print
7
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28

How to Count Number of Words in String - Java


Coding Exercise
The string is very popular among the Interviewer, and you are bound to see some questions on any programming
interview, Java Interviews are no exception. Questions based on Java fundamentals like why String is Immutable
in Java to questions based on coding skills e.g. reverse String using recursion in Java, String has always troubled
candidates. In this article, we will see a similar question, how to count the number of words in Java String. Before
jumping to the solution, just read below to make sure what a word means here. It's a sequence of one or more non-
space characters.

We will see two examples to find the number of words in Java String, the first one is based upon pure logic,
where it goes through all characters from String and then count each word. Second is more interesting than the
first one, here we have used a regular expression to find all words.

We split String by white space, passing \\s+ means greedy search i.e. it includes one or more white spaces.

Problem :

Write a function in Java which accepts a string argument and returns the number of words in it. A word is a
sequence of one or more non-space character i.e. any character other than '' (empty String). This should be your
method signature :

public int wordCount(String word);

This method should return 5 if passed "Java is best programming language" and return 3 if passed "Java is great".
Similarly a call to wordCount(" ") should return 0.

Solution :
In order to implement this method we need to assume that two words are separated by space. We also need to
ignore leading, trailing and multiple spaces between words. One way to solve this problem is to split String by
space and then count number of parts. We will see two solution of this problem, here is the first one .

How find number of words String - 2 Examples


In this sample program, we have two methods, first we will count number of words without using regular
expression, and second will do the same but using regex.

/**
* Java Program to count number of words in String
* * @author Javin
*/
public class WordCounterProblem{
/*
* This method return word count without using regular expression
*/
public int wordcount(String word) {
if (word == null || word.isEmpty()) {
return 0;
}
int count = 0;
char ch[] = new char[word.length()];
for (int i = 0; i < word.length(); i++) {
ch[i] = word.charAt(i);
if (((i > 0) && (ch[i] != ' ') && (ch[i - 1] == ' ')) || ((ch[0] != '
') && (i == 0))) {
count++;
}
}
return count;
}
/*
* Counting number of words using regular expression.
*/
public int countWord(String word) {
if (word == null) {
return 0;
}
String input = word.trim();
int count = input.isEmpty() ? 0 : input.split("\\s+").length;
return count;
}

How to Find All Permutations of String in Java


using Recursion
How to find all permutation of a String using recursion is one of the tricky coding questions from
programming job interviews. I have first seen this question in my college exam when we were asked to code the
solution using C or C++ language. Since then I have seen this question many times at various written tests and
Java interviews for a junior developer position. It does not only serve as a good question to check whether the
candidate understands recursion but also its one of the better Java programming exercise for beginners.

Typically, you will be asked to write a method, which accepts a String and print all permutations or may return all
permutations in a List for a junior developer position. Depending upon the company you are going for an
interview, they may ask you to code on IDE like Eclipse or NetBeans, or simply write code in plain paper, so be
prepared for both.

There are two main ways to solve this problem, using loops or by using recursion, the second one is what the
interviewer expects. Since recursion is a tricky programming concept to master, it's not easy for every
programmer to solve this problem on the fly, especially if you are not coding on a daily basis or don't have that
highly sought after code sense.

Solution 1 - Final All Permutations of given String


Using Recursion and Loop
Now let's get back to the problem, Permutation refers to ordering of characters but it takes position into account
i.e. if you have String "ab" then it will have just 2 permutations "ab" and "ba", because position of character
in both String are different.

Similarly for a String of n characters there are !n (factorial of n) permutations are possible e.g. for a String of 3
characters like "xyz" has 6 possible permutations, xyz, xzy, yxz, yzx, zxy, zyx as seen in our example. As I told
there are two ways to solve this problem either by using for loop (iterative algorithm) or by using recursion, but
most elegant solution is combination of both loop and recursion.

If you remember the factorial problem you know that factorial is naturally recursive i.e. factorial of n is nothing
but n * factorial of n -1. Similarly, permutations are also a recursive problem e.g. permutation of n characters is
nothing but fixing one character and calculating permutation of n - 1 characters e.g. in the case of "xyz", you
can fix "x" and calculate permutation of "yz".

In order to calculate all permutation of a String, you need to repeat this exercise for all characters one at a time.
This is where for loop comes into the picture. So, this solution uses both for loop and recursion to print all
permutation of given String.

In the case of recursion, the most important question is the base case, because that is responsible for stopping
recursive call. If you don't have a base case then your program will eventually terminate with
java.lang.StackOverFlowError.

In this problem, our base case is a permutation of empty String, which is nothing but the empty String itself. After
each call, problem set is reduced and inches towards the base case, when it reaches there stack starts rolling down
and calculates the result.

Java Program to Print All Permutation of a String

Here is our sample Java program to print all permutations of given String using recursive algorithm. It uses both
loop and recursive call to solve this problem. It also demonstrate a technique of hiding your implementation detail
using a private method and exposing a much cleaner public method as API. In our solution, we have two
permutation method, one is public and other is private.

First method is clean and exposed to client but second method require you to pass an empty String as initial value
of perm parameter which is used to store intermediate permutation of String.

If you expose this method to client then it will wonder about this empty String, since it's part of implementation,
its better to hide and get rid of it as soon as you have a better algorithm to solve this problem, how about taking it
as an exercise?

/**
* Java program to find all permutations of a given String using recursion.
* For example, given a String "XYZ", this program will print all 6 possible
permutations of
* input e.g. XYZ, XZY, YXZ, YZX, ZXY, XYX
*
* @author Javin Paul
*/
public class StringPermutations {

public static void main(String args[]) {


permutation("123");
}
/*
* A method exposed to client to calculate permutation of String in Java.
*/
public static void permutation(String input){
permutation("", input);
}

/*
* Recursive method which actually prints all permutations
* of given String, but since we are passing an empty String
* as current permutation to start with,
* I have made this method private and didn't exposed it to client.
*/
private static void permutation(String perm, String word) {
if (word.isEmpty()) {
System.err.println(perm + word);

} else {
for (int i = 0; i &lt; word.length(); i++) {
permutation(perm + word.charAt(i), word.substring(0, i)
+ word.substring(i + 1, word.length()));
}
}

}
}

Output:
123
132
213
231
312
321
Like everything else, practice is your friend, doing this kind of coding exercises on a daily basis, solving
programming puzzles and doing more complex programs available on internet sites like project Euler, TopCoder
will help you to build confidence in your coding and problem-solving skill.

Explanation of Code :
All code for calculating permutation of String is inside permutation(String perm, String
word) method, I have purposefully made this method private because of additional parameter I am passing as an
initial value of permutation.

This demonstrates a technique of hiding implementation detail from a client and exposing much cleaner API to
client e.g. just permutation(String input) method, passing empty String is an implementation detail
and ugly for a client to pass whenever it needs to calculate permutation. It is also an exercise for you to see if you
can improve the code by getting rid of that empty String.

Algorithm is nothing but keeping one character fix and then calculating permutations of others. Crux of program
is in following code segment :

for (int i = 0; i &lt; word.length(); i++) {


permutation(perm + word.charAt(i), word.substring(0, i)
+ word.substring(i + 1, word.length()));
}

Here we have a for loop to go through each character of String e.g. for input "123" this loop will run three times.
In each iteration, we are making a recursive call to function itself i.e. permutation(String perm,
String word) method, where the first parameter is used to store the result.

After 1st iteration perm (first parameter of permutation() method) will be "" + 1 as we are doing
word.charAt(i) and i is zero. Next, we take out that character and pass the remaining characters to
permutation method again e.g. "23" in the first iteration. Recursive call ends when it reaches to base case i.e.
when remaining word becomes empty, at that point "perm" parameter contains a valid permutation to be printed.
You can also store it into a List if you want to.

Here is a nice diagram which visually shows what this algorithm does :
That's all on how to find all permutations of a String in Java using recursion. It's a very good exercise for
preparing Java coding interviews. Why not you give it a try and come up with another solution? also could you
calculate complexity of this algorithm, to me it looks n*!n because loop will run for n times and for each n, we
will call permutation method. Also, how about writing some JUnit test cases to see if this solution works for
various input e.g. empty String, one letter String, many letters String, String with duplicate characters etc? It's a
good practice to become hands-on writing JUnit tests.

How to Remove Duplicates from Array Without


Using Java Collection API
The main problem, while dealing with an array is not finding duplicates, it's about removing them. Since an array
is a static, fixed-length data structure, you can not change its length. This means, deleting an element from an
array requires creating a new array and copying content into that array.

If your input array contains lots of duplicates then this may result in lots of temporary arrays. It also increases the
cost of copying content, which can be very bad. Given this restriction, you need to come out with a strategy to
minimize both memory and CPU requirements.

Java Program to remove duplicates from integer array without


Collection

In this program, we have not used any collection class to remove duplicates, earlier, I had shown you a way
to remove duplicates from ArrayList, which was using LinkedHashSet. You can still use that solution if the
interviewer doesn't mention without Collection specifically.

All you need to do is to convert your array into ArrayList first then subsequently create a LinkedHashSet
from that ArrayList. In this example, we are removing duplicates from the array by not copying them into
result array, this solution is not actually deleting duplicates instead it replacing it with default value i.e. zero.

Now, let's see our Java solution for removing duplicates from integer array:

import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Java program to remove duplicates from this array. You don't
* need to physically delete duplicate elements, replacing with null, or
* empty or default value is ok.
*
* @author http://javarevisited.blogspot.com
*/
public class TechnicalInterviewTest {

private static final Logger logger =


LoggerFactory.getLogger(TechnicalInterviewTest.class);

public static void main(String args[]) {

int[][] test = new int[][]{


{1, 1, 2, 2, 3, 4, 5},
{1, 1, 1, 1, 1, 1, 1},
{1, 2, 3, 4, 5, 6, 7},
{1, 2, 1, 1, 1, 1, 1},};

for (int[] input : test) {


System.out.println("Array with Duplicates : " +
Arrays.toString(input));
System.out.println("After removing duplicates : " +
Arrays.toString(removeDuplicates(input)));
}
}

/*
* Method to remove duplicates from array in Java, without using
* Collection classes e.g. Set or ArrayList. Algorithm for this
* method is simple, it first sort the array and then compare adjacent
* objects, leaving out duplicates, which is already in the result.
*/
public static int[] removeDuplicates(int[] numbersWithDuplicates) {

// Sorting array to bring duplicates together


Arrays.sort(numbersWithDuplicates);

int[] result = new int[numbersWithDuplicates.length];


int previous = numbersWithDuplicates[0];
result[0] = previous;

for (int i = 1; i < numbersWithDuplicates.length; i++) {


int ch = numbersWithDuplicates[i];

if (previous != ch) {
result[i] = ch;
}
previous = ch;
}
return result;

}
}

Output :
Array with Duplicates : [1, 1, 2, 2, 3, 4, 5]
After removing duplicates : [1, 0, 2, 0, 3, 4, 5]
Array with Duplicates : [1, 1, 1, 1, 1, 1, 1]
After removing duplicates : [1, 0, 0, 0, 0, 0, 0]
Array with Duplicates : [1, 2, 3, 4, 5, 6, 7]
After removing duplicates : [1, 2, 3, 4, 5, 6, 7]
Array with Duplicates : [1, 2, 1, 1, 1, 1, 1]
After removing duplicates : [1, 0, 0, 0, 0, 0, 2]

That's it about how to remove duplicates from an array in Java without using Collection class. As I said
before, this solution is not perfect and has some serious limitation, which is an exercise for you to find out. One
hint I can give is that array itself can contain default value as duplicates e.g. 0 for int, even if you use any Magic
number e.g. Integer.MAX_VALUE, you can not be certain that they will not be part of the input.

Regarding removing duplicate permanently from result array, one approach could be to count a number of
duplicates and then create an array of right size i.e. length - duplicates, and then copying content from
intermediate result array to final array, leaving out elements which are marked duplicate.

How to find Largest Prime Factor of a Number in


Java
One of the common programming is to write a program to find the largest prime factor of a number. Like any
other programming problem, you need to build the logic to solve this problem. Before solving the problem, let's
revise the concept of number theory. Prime factors of a positive integer are the prime numbers that divide the
number exactly i.e. without any remainder, and prime factorization is the process of finding all prime numbers
when multiplied together make original number.

A positive integer can have multiple prime factors, our challenge is to find the largest prime factor of a number.
For example, 6 has two prime factors 2 and 3, your program should return 3 because that's the largest prime
factors.

In one of the earlier problems, we have learned how to find the prime factors of a number in Java and we will use
a similar logic here, but instead of returning a list of prime factors, we will only return the largest prime factor.

Java Program to Find Largest Prime Factor of an


Integer
Problem: Write a program to find the largest prime factor of a positive integer in Java. If we pass 15 to your
program, it should return 5, and if we pass 6 to your program it should return 3.

Solution: As we learned a number is called prime factor if it is prime number and it can divide the number
exactly. Another property of prime factor is that if we keep dividing the number by prime factor then it will either
fully divide the number or produce another prime factor e.g. if we need to find the prime factors of 16 then
starting from 2 if keep dividing, eventually dividend become 1, so 2 is the only prime factor of 16.

On the other hand, if we need to find a prime factor of 15, then we first try to divide it by 2, but since its not
divisible by 2, we move to the next number which is 3. Since 3 can divide 15, it produces another prime number
5, now 5 is not divisible by anything other than 5, so 3 and 5 become prime factor of 15.

Algorithm: In our program, we have used the same logic. We start with 2, the smallest prime number and try to
divide the number, if number is divisible then we keep dividing it by same number until its not divisible any
more. Now we move to next number, the largest number which is able to fully divide the input is our largest
prime factor. This would be more clear when you see the actual program.

import java.util.Random;
import java.util.Scanner;

/**
* Java program to find and print largest prime factor of an integer number. for
* example number 6 has two prime factors 2 and 3, but 3 is the largest prime
* factor of 6. input 15 output 5
*
* @author Javin Paul
*/
public class LargetPrimeFactor{

public static void main(String args[]) {


System.out.printf("Largest prime factor of number '%d' is %d %n",
6, largestPrimeFactor(6));
System.out.printf("highest prime factor of number '%d' is %d %n",
15, largestPrimeFactor(15));
System.out.printf("Biggest prime factor of number '%d' is %d %n",
392832, largestPrimeFactor(392832));
System.out.printf("Largest prime factor of number '%d' is %d %n",
1787866, largestPrimeFactor(1787866));
}

/**
* @return largest prime factor of a number
*/
public static int largestPrimeFactor(long number) {
int i;
long copyOfInput = number;

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


if (copyOfInput % i == 0) {
copyOfInput /= i;
i--;
}
}

return i;
}

Output:
Largest prime factor of number '6' is 3
highest prime factor of number '15' is 5
Biggest prime factor of number '392832' is 31
Largest prime factor of number '1787866' is 893933
You can see from output that our program is working properly, for 6 the largest prime factor is 3 and for 15 its 5.
Here is our unit test to check couple of more numbers :

How to Check if Integer Number is Power


of Two in Java - 3 examples
How to check if an integer number is a power of 2 in Java is one of the popular programming interview
questions and has been asked in many interviews. Surprisingly, this problem which looks simple enough to
answer doesn't turn out that simple if for many developers. Many Java programmers, both freshers and less
experienced, struggle to write code for a function, which can check if the number is the power of 2 or not.
There could be many different reasons for that, but it’s expected to at least come up with a brute force
solution. For those who are familiar with bitwise operators in Java, how positive and negative numbers are
represented in binary format, this exercise is quite easy.

Since negative numbers are represented as 2's complement value in Java, you can easily find if any number
is the power of 2 or not by looking at its bit pattern. Remember checking for the power of two is different
than checking if a number is even or odd, that’s another thing to note. A number can be even, but it’s not
necessary to be a power of two, e.g. 6 is even but it’s not a power of two.

3 ways to check if a number is the power of two or not

In this article, we will see 3 simple examples to check if any integer number is power of 2 or not. We have
three methods, which uses bitwise operator, brute force way and bit shit operators to solve this problem.

Method which uses bitwise operators can not check if zero is power of 2 or not, and only work for integer
number which is greater than or equal to 1. here are code example of 3 simple method to find out if a
number is power of 2 or not :

public class PowerOf2Test {

public static void main(String args[]) {

int[] numbers = {0,1,2,6,8};

for(int num: numbers){


System.out.println("isPowerOfTwo()-- is " + num + " power of two
in Java :" + isPowerOfTwo(num));
System.out.println("powerOfTwo()-- is " + num + " power of two
in Java :" + powerOfTwo(num));
System.out.println("checkPowerOfTwo()-- is " + num + " power of
two in Java :" + checkPowerOfTwo(num));
System.out.println("--------------------------------------------
---------------");
}

}
/*
* checking if number is power of 2 using bit shift operator in java
* e.g. 4 in binary format is "0000 0000 0000 0000 0000 0000 0000 0100";
* and -4 is "1111 1111 1111 1111 1111 1111 1111 1100";
* and 4&-4 will be "0000 0000 0000 0000 0000 0000 0000 0100"
*/
private static boolean isPowerOfTwo(int number) {
if(number <0){
throw new IllegalArgumentException("number: " + number);
}
if ((number & -number) == number) {
return true;
}
return false;
}

/*
* checking if number is power of 2 using brute force
* starts with 1, multiplying with 2 it will eventually be same as
original number
*/
private static boolean powerOfTwo(int number){
int square = 1;
while(number >= square){
if(number == square){
return true;
}
square = square*2;
}
return false;
}

/*
* find if an integer number is power of 2 or not using bit shift
operator
*/

private static boolean checkPowerOfTwo(int number){


if(number <0){
throw new IllegalArgumentException("number: " + number);
}
return ((number & (number -1)) == 0);
}
}

Output:
isPowerOfTwo()-- is 0 power of two in Java :true
powerOfTwo()-- is 0 power of two in Java :false
checkPowerOfTwo()-- is 0 power of two in Java :true
-----------------------------------------------------------
isPowerOfTwo()-- is 1 power of two in Java :true
powerOfTwo()-- is 1 power of two in Java :true
checkPowerOfTwo()-- is 1 power of two in Java :true
-----------------------------------------------------------
isPowerOfTwo()-- is 2 power of two in Java :true
powerOfTwo()-- is 2 power of two in Java :true
checkPowerOfTwo()-- is 2 power of two in Java :true
-----------------------------------------------------------
isPowerOfTwo()-- is 6 power of two in Java :false
powerOfTwo()-- is 6 power of two in Java :false
checkPowerOfTwo()-- is 6 power of two in Java :false
-----------------------------------------------------------
isPowerOfTwo()-- is 8 power of two in Java :true
powerOfTwo()-- is 8 power of two in Java :true
checkPowerOfTwo()-- is 8 power of two in Java :true
-----------------------------------------------------------

That’s all on this article about checking if a number I power of two or not. Let us know if you find
another way to verify if number is power of two.

How to Find Middle Element of Linked List


in Java in Single Pass
ow do you find the middle element of LinkedList in one pass is a programming question often asked Java and
non-Java programmers in telephonic Interview. This question is similar to checking palindrome or calculating the
factorial, where the Interviewer sometimes also asks to write code. In order to answer this question candidate
must be familiar with the LinkedList data structure i.e. In the case of the singly LinkedList, each node of Linked
List contains data and pointer, which is the address of the next Linked List and the last element of Singly Linked
List points towards the null. Since in order to find the middle element of the Linked List you need to find the
length of the linked list, which is counting elements till the end i.e. until you find the last element of the Linked
List.

What makes this data structure Interview question interesting is that you need to find the middle element of
LinkedList in one pass and you don’t know the length of LinkedList.

This is where candidates' logical ability puts into the test, whether he is familiar with space and time trade-off or
not etc.

As if you think carefully you can solve this problem by using two pointers as mentioned in my last post on How
to find the length of the Singly Linked List in Java.

By using two pointers, incrementing one at each iteration and other at every second iteration. When the first
pointer will point at end of Linked List, the second pointer will be pointing at a middle node of the Linked List.

In fact, this two pointer approach can solve multiple similar problems like how to find the third node from last in
a Linked List in one Iteration or how to find an Nth element from last in a Linked List. In this Java programming
tutorial, we will see a Java program that finds the middle element of Linked List in one Iteration.

Btw, if you are new to Algorithms and Data Structure and not familiar with an essential data structure like a
linked list, array or binary tree then I suggest you go through a good, comprehensive online course like Data
Structures and Algorithms: Deep Dive Using Java to learn the basics and brush up the fundamentals.

How to Find Middle Element of LinkedList in One Pass

Here is a complete Java program to find the middle node of Linked List in Java. Remember LinkedList class here
is our custom class and don’t confuse this class with java.util.LinkedList is a popular Collection class in Java.

In this Java program, our class LinkedList represents a linked list data structure that contains a collection of the
node and has a head and tail.

Each node contains data and addresses part. The main method of LinkedListTest class is used to simulate
the problem, where we created Linked List and added few elements on it and then iterate over them to find the
middle element of linked list in one pass in Java.

Java Program to Find the Middle Node of a Linked list in a Single-pass

import test.LinkedList.Node;

/**
* Java program to find middle element of linked list in one pass.
* In order to find middle element of a linked list
* we need to find the length first but since we can only
* traverse linked list one time, we will have to use two pointers
* one which we will increment on each iteration while
* other which will be incremented every second iteration.
* So when the first pointer will point to the end of a
* linked list, second will be pointing to the middle
* element of a linked list
*
* @author Javin Paul
*/
public class LinkedListTest {

public static void main(String args[]) {


//creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList();
LinkedList.Node head = linkedList.head();
linkedList.add( new LinkedList.Node("1"));
linkedList.add( new LinkedList.Node("2"));
linkedList.add( new LinkedList.Node("3"));
linkedList.add( new LinkedList.Node("4"));

//finding middle element of LinkedList in single pass


LinkedList.Node current = head;
int length = 0;
LinkedList.Node middle = head;

while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}

if(length%2 == 1){
middle = middle.next();
}

System.out.println("length of LinkedList: " + length);


System.out.println("middle element of LinkedList :
" + middle);

class LinkedList{
private Node head;
private Node tail;

public LinkedList(){
this.head = new Node("head");
tail = head;
}

public Node head(){


return head;
}

public void add(Node node){


tail.next = node;
tail = node;
}

public static class Node{


private Node next;
private String data;

public Node(String data){


this.data = data;
}

public String data() {


return data;
}
public void setData(String data) {
this.data = data;
}

public Node next() {


return next;
}

public void setNext(Node next) {


this.next = next;
}

public String toString(){


return this.data;
}
}
}

Output:
length of LinkedList: 4
the middle element of LinkedList: 2

That’s all on How to find the middle element of LinkedList in one pass. As I said this is a good interview
question to separate programmers from non-programmers. Also, the technique mentioned here to find the middle
node of LinkedList can be used to find the 3rd element from Last or nth element from last in a LinkedList as well.

How to Check if a Number is Binary in


Java - Programming Problem
Today we will take a look at another simple programming exercise, write a program to check if a number is
binary in Java. A number is said to be binary if it only contains either 0 or 1, for example, 1010 is a binary
number but 1234 is not. You can not any library method to solve this problem, you need to write a function to
check if the given number is binary, you can use basic constructs of Java programming language e.g. operators,
keywords, control statements, etc. If you are a regular reader of Javarevisited, then you know that I love to share
simple programming problems here.

Programming interview questions serve two purposes, first, they help beginners to apply their basic knowledge to
do something which looks challenging at first, and second, they serve as good coding questions to differentiate
candidates on Java interviews between who can program and who can not.

The classic FizzBuzz is one of such problems but there are lot many, e.g. Prime numbers, Fibonacci series, or
factorial.

But if you truly want to test your candidate then you need to give them some questions which are not so popular.
If a candidate can apply his programming knowledge to a problem he is seeing the first time, he is probably going
to perform better than the candidate who has already seen the problem.

That's why I was always looking at programming problems, which are not difficult to solve but has some element
of freshness and not so common. This problem of checking whether a number is binary or not is not very different
from converting decimal to binary, but it will pose a challenge for those programmers who can't code.

Java Program check if a number is binary in Java


The logic of finding if a number is binary is extremely simple, probably simpler than FizzBuzz itself, all you need
to do is to check every digit of the number to see if they are greater than 1 or not. If any digit is greater than 1 then
it's not binary.

For first-timers challenge is how to write a loop to check every digit, well you need to remember one of the
common tricks of programming. If you divide a number by 10 e.g. number/10, you reduce one digit from it and
if you use the remainder operator e.g. number%10 then you will get the last digit of the number.

For example, 1234/10 will return 123 which means last digit 4 is removed and 1234%10 will return 4, which
is the last digit. By using these two operators you can easily write a loop that can go through each digit and can
check if it's greater than 1 or not. This property is very useful in solving problems that involve checking each
digit e.g. finding if a number is palindrome or reversing a number.

Java Program to check if the given number is binary or not

Following is a complete Java program to show you how you can check if a given number is binary or not. It
contains one method called isBinary(int number), which accepts a number and returns true if it's binary
otherwise false.

/* Java program to check if a number is binary or not. A number is said to be


* binary, if it only contains 0 and 1.
*
* @author
*/
public class Binary{

public static void main(String args[]) {

System.out.printf("Does number %d is a binary number? %b %n",


101, isBinary(101));
System.out.printf("Does integer %d is a binary number? %b %n",
121, isBinary(121));
System.out.printf("Does %d is a binary number? %b %n",
1011, isBinary(1011));
System.out.printf("Does number %d is a binary number? %b %n",
111111, isBinary(111111));
System.out.printf("Does %d is a binary number? %b %n",
1321, isBinary(1321));
}

/** Java function to check if an integer is a binary number or not.


*/
public static boolean isBinary(int number) {
int copyOfInput = number;

while (copyOfInput != 0) {
if (copyOfInput % 10 > 1) {
return false;
}
copyOfInput = copyOfInput / 10;
}
return true;
}

Output:
Does number 101 is a binary number? true
Does integer 121 is a binary number? false
Does 1011 is a binary number? true
Does number 111111 is a binary number? true
Does 1321 is a binary number? false

You can see from the output that our function is behaving correctly if you enter 101 it returned true because it's
a binary number, it only contains zero and one. On the other hand, if you call isBinary() method with 121 it
returned false because 121 is not binary, it contains digit 2 which is not allowed in the binary number system.

How to check if two String are Anagram in Java


- Program Example
Write a Java program to check if two String is an anagram of each other, is another good coding
question asked at fresher level Java Interviews. This question is on a similar level of finding the
middle element of LinkedList in one pass and swapping two numbers without using temp variable.
By the way, two String is called anagram, if they contains the same characters but on different
order e.g. army and mary, stop and pots, etc. Anagrams are actually a mix-up of characters in
String. If you are familiar with String API, i.e. java.lang.String then you can easily solve this
problem.

In order to check if Strings are anagram, you need to get there character array and see if they are
equal or not. Though you can also use indexOf(), substring(), and StringBuffer or
StringBuilder class to solve this question.

In this Java program, we will see 3 ways to solve this interview questions, and check if two String
are anagram or not. By the way, if you are preparing for Java interview, it's good to prepare some
data structures and algorithms questions as well. More often, there is one or more questions from
programming, coding, and logic in these interviews.

Java program to check if String is an anagram

As I said, there are multiple ways to find if two string are anagram or not. The classical way is
getting a character array of each String, and then comparing them, if both char array is equal then
Strings are anagram. But before comparing, make sure that both Strings are in the same case e.g.
lowercase or uppercase and character arrays are sorted because equals method of Arrays, return
true, only if the array contains the same length, and each index has the same character.

For simplicity, I have left checking if String is null or empty and converting them into uppercase or
lowercase, you can do that if you want. If Interviewer ask you to write production quality code,
then I would suggest definitely put those checks and throw IllegalArgumentException for null
String or you can simply return false.

I would personally prefer to return false rather than throwing Exception, similar to equals()
method. Anyway, here are three ways to check if two String are Anagram or not. I have also
included a JUnit Test to verify various String which contains both anagram and not.
import java.util.Arrays;

/**
* Java program - String Anagram Example.
* This program checks if two Strings are anagrams or not
*
* @author Javin Paul
*/
public class AnagramCheck {
/*
* One way to find if two Strings are anagram in Java. This method
* assumes both arguments are not null and in lowercase.
*
* @return true, if both String are anagram
*/
public static boolean isAnagram(String word, String anagram){
if(word.length() != anagram.length()){
return false;
}

char[] chars = word.toCharArray();

for(char c : chars){
int index = anagram.indexOf(c);
if(index != -1){
anagram = anagram.substring(0,index) + anagram.substring (index +1,
anagram.length());
}else{
return false;
}
}

return anagram.isEmpty();
}

/*
* Another way to check if two Strings are anagram or not in Java
* This method assumes that both word and anagram are not null and lowercase
* @return true, if both Strings are anagram.
*/
public static boolean iAnagram(String word, String anagram){
char[] charFromWord = word.toCharArray();
char[] charFromAnagram = anagram.toCharArray();
Arrays.sort(charFromWord);
Arrays.sort(charFromAnagram);

return Arrays.equals(charFromWord, charFromAnagram);


}

public static boolean checkAnagram(String first, String second){


char[] characters = first.toCharArray();
StringBuilder sbSecond = new StringBuilder(second);

for(char ch : characters){
int index = sbSecond.indexOf("" + ch);
if(index != -1){
sbSecond.deleteCharAt(index);
}else{
return false;
}
}

return sbSecond.length()==0 ? true : false;


}
}
JUnit Test Case for String Anagram Exmaple
here is our JUnit tests for all three 3 methods of AnagramCheck class, we have actually tested all method with
similar set of input.
import org.junit.Test;
import static org.junit.Assert.*;

/**
* JUnit test class to test various anagram program for various String input.
*/
public class StringAnagramTest {

@Test
public void testIsAnagram() {
assertTrue(AnagramCheck.isAnagram("word", "wrdo"));
assertTrue(AnagramCheck.isAnagram("mary", "army"));
assertTrue(AnagramCheck.isAnagram("stop", "tops"));
assertTrue(AnagramCheck.isAnagram("boat", "btoa"));
assertFalse(AnagramCheck.isAnagram("pure", "in"));
assertFalse(AnagramCheck.isAnagram("fill", "fil"));
assertFalse(AnagramCheck.isAnagram("b", "bbb"));
assertFalse(AnagramCheck.isAnagram("ccc", "ccccccc"));
assertTrue(AnagramCheck.isAnagram("a", "a"));
assertFalse(AnagramCheck.isAnagram("sleep", "slep"));

@Test
public void testIAnagram() {
assertTrue(AnagramCheck.iAnagram("word", "wrdo"));
assertTrue(AnagramCheck.iAnagram("boat", "btoa"));
assertFalse(AnagramCheck.iAnagram("pure", "in"));
assertFalse(AnagramCheck.iAnagram("fill", "fil"));
assertTrue(AnagramCheck.iAnagram("a", "a"));
assertFalse(AnagramCheck.iAnagram("b", "bbb"));
assertFalse(AnagramCheck.iAnagram("ccc", "ccccccc"));
assertFalse(AnagramCheck.iAnagram("sleep", "slep"));

@Test
public void testcheckAnagram() {
assertTrue(AnagramCheck.checkAnagram("word", "wrdo"));
assertFalse(AnagramCheck.checkAnagram("b", "bbb"));
assertFalse(AnagramCheck.checkAnagram("ccc", "ccccccc"));
assertTrue(AnagramCheck.checkAnagram("a", "a"));
assertFalse(AnagramCheck.checkAnagram("sleep", "slep"));
assertTrue(AnagramCheck.checkAnagram("boat", "btoa"));
assertFalse(AnagramCheck.checkAnagram("pure", "in"));
assertFalse(AnagramCheck.checkAnagram("fill", "fil"));

}
}

Output
Testsuite: StringAnagramTest
Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 0.094 sec

Our AnagramCheck class contains 3 static methods to verify if Strings are anagram or not. First one,
takes character array of first String and loop through it, then finds that character in second String, and
deletes it by using substring method. If second String doesn't contains character than method return
false immediately. At the end of test if second String is empty than both Strings are anagram because
they contains same set of characters. To improve performance, we have checked length at very start of
this method, as two String with different length can not be anagram of each other. Third method is
exactly same of first one, except, it uses deleteCharAt(int index) method of StringBuilder for
deleting characters.

How to check if a number is a palindrome


or not in Java - Example
How to check if a number is a palindrome or not is a variant of popular String interview question how to
check if a String is a palindrome or not. A number is said to be a palindrome if the number itself is equal to
reverse of number e.g. 313 is a palindrome because the reverse of this number is also 313. On the other
hand 123 is not a palindrome because the reverse of 123 is 321 which is not equal to 123, i.e. original
number. In order to check if a number is a palindrome or not we can reuse the logic of How to reverse a
number in Java.

I have also seen programmer solving this question by first converting an integer to String and then
reversing String using the reverse() method of StringBuffer and then converting String back to
Integer, which is not a correct way because you are using Java API.

Java program to check if a number is palindrome or not

Here is a simple Java program which finds if a number is a palindrome or not. This program does not
use any API method instead it uses division and remainder operator of Java programming language to
determine if number is palindrome or not. Programming logic to reverse a number is encapsulate in
reverse() method and isPalindrome(int number) reuse that logic to test if a number is
palindrome or not.

import java.util.Scanner;
/**
* This Java program takes an input number from command line and integer
array
* and check if number is palindrome or not. A number is called palindrome
* if number is equal to reverse of number itself.
*
* @author Javin Paul
*/
public class PalindromeTest {

public static void main(String args[]){

Scanner scanner = new Scanner(System.in);


//int number = scanner.nextInt();
int[] numbers = {1, 20, 22, 102, 101, 1221, 13321, 13331, 0, 11};

for(int number: numbers){


System.out.println("Does number : "
+ number +" is a palindrome? " + isPalindrome(number));
}
}

private static boolean isPalindrome(int number) {


if(number == reverse(number)){
return true;
}
return false;
}
private static int reverse(int number){
int reverse = 0;

while(number != 0){
reverse = reverse*10 + number%10;
number = number/10;
}

return reverse;
}

Output
Does number : 1 is a palindrome? true
Does number : 20 is a palindrome? false
Does number : 22 is a palindrome? true
Does number : 102 is a palindrome? false
Does number : 101 is a palindrome? true
Does number : 1221 is a palindrome? true
Does number : 13321 is a palindrome? false
Does number : 13331 is a palindrome? true
Does number : 0 is a palindrome? true
Does number : 11 is a palindrome? true

3 Ways to Find Duplicate Elements in an


Array - Java
There are multiple ways to find duplicate elements in an array in Java and we will see three of them in this
program. The solution and logic shown in this article are generic and apply to an array of any type e.g. String
array or integer array or array of any object. One of the most common ways to find duplicates is by using the
brute force method, which compares each element of the array to every other element. This solution has the time
complexity of O(n^2) and only exists for academic purposes. You shouldn't be using this solution in the real
world.
How to find duplicates in Java array?

In the first paragraph, I have given you a brief overview of three ways to find duplicate elements from Java array.
Now, let's understand the logic behind each of those solutions in little more detail.

Solution 1:
Our first solution is very simple. All we are doing here is to loop over an array and comparing each element to
every other element. For doing this, we are using two loops, inner loop, and outer loop. We are also making sure
that we are ignoring comparing of elements to itself by checking for i != j before printing duplicates. Since we are
comparing every element to every other element, this solution has quadratic time complexity i.e. O(n^2). This
solution has the worst complexity in all three solutions.

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


for (int j = i + 1 ; j < names.length; j++) {
if (names[i].equals(names[j])) {
// got the duplicate element
}
}
}

How to Find Top Two Maximum Number from Integer


array in Java
Hello guys, I have been sharing a lot of Programming interview questions and coding problems to learn
programming better which is appreciated by you guys. In this post, I have come with another simple programming
problems for Java beginners. I love to share short programming problems because they help in developing
programming sense. Many people will argue against simple problems like prime numbers, palindrome, and
factorial, but I really find them useful, especially for beginners. A beginner is far away to solve a complex data
structure problem or even more complex problems like those appear in TopCoder or other programming sites.
Programmers learn gradually and they need the joy of doing something and seeing results much quicker than any
other. Small success motivates them.

Anyway, here is our problem statement, you need to write a Java program to find the top two maximum numbers
in the given array. You can not use any sorting functions and you should iterate the array only once. The use of
any kind of collection class like TreeSet or LinkedHashSet is also not allowed.

For example, if given integer array is [20, 34, 21, 87, 92, 2147483647] then the first maximum is
2147483647 and the second maximum is 92. Bonus points are for those, who can also write JUnit test cases,
more test scenarios, more points.

Few more bonus points for those who can write code to deal with a really large array, something which may not
entirely fit on memory. Btw, a good knowledge of fundamental data structure like an array is very important for
every programmer.

How to Find Top Two Maximum Numbers from


Integer Array
Here is our sample Java program, It solves the problem following the given problem statement and under
constraints states. For example, it doesn't use any sorting algorithm like bubble sort or quicksort, or
Collections.sort() method.

As I said before, this kind of program is a good exercise for mastering basic building blocks of any programming
language like loops, if-else block, and learning relational operator like less than (<) and greater than (>).

It takes advantage of the if-else control statement to solve this problem. All we do is we start with two
variables as max1 and max2 and initialized them with Integer.MIN_VALUE, which is the limit of minimum
value.

Now we iterate through the array and compare each number against these two numbers, if the current number is
greater than max1 then max1 = number and max2 = max1. Otherwise if it only greater than max2 then
we only update max2 with the current number.

At the end of the iteration, max1 and max2 point to the top two numbers from a given array. You see the
problem solved without any utility class or third-party library. Though, if you are new to Java and not very
familiar with the conditional statements in Java like the if-else-if block or switch statement then also recommend
you check out a comprehensive Java course like The Complete Java MasterClass to learn Java better. This is
also very affordable and you can buy in just $9.99 on crazy Udemy sales.

Java Program To Find Top Two Numbers from Integer Array


Now, without wasting any more of your time, here is our complete code example which you can copy-paste in
Eclipse or your favorite IDE and run it. You can also save this code in a file called ToTwoMaximum.java and run
it from command prompt.

import java.util.Arrays;
/**
* Java program to find top two maximum numbers from an integer
array.
*
* @author http://java67.blogspot.com
*/
public class TopTwoMaximum{

public static void main(String args[]) {


topTwo(new int[]{20, 34, 21, 87, 92, Integer.MAX_VALUE});
topTwo(new int[]{0, Integer.MIN_VALUE, -2});
topTwo(new int[]{Integer.MAX_VALUE, 0, Integer.MAX_VALUE});
topTwo(new int[]{1, 1, 0});
}

public static void topTwo(int[] numbers) {


int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
for (int number : numbers) {
if (number > max1) {
max2 = max1;
max1 = number;
} else if (number > max2) {
max2 = number;
}
}

System.out.println("Given integer array : "


+ Arrays.toString(numbers));
System.out.println("First maximum number is : " + max1);
System.out.println("Second maximum number is : " + max2);
}

Output:
Given integer array : [20, 34, 21, 87, 92, 2147483647]
First maximum number is : 2147483647
Second maximum number is : 92
Given integer array : [0, -2147483648, -2]
First maximum number is : 0
Second maximum number is : -2
Given integer array : [2147483647, 0, 2147483647]
First maximum number is : 2147483647
Second maximum number is : 2147483647
Given integer array : [1, 1, 0]
First maximum number is : 1
Second maximum number is : 1

From the output, you can see that our method the topTwo(int[] numbers) are working properly for
different sets of inputs. I have chosen the main method over the JUnit test for testing my code, which is quick and
dirty.

Java Program to find the most repeated word in


a text file
In this program, we need to find the most repeated word present in given text file. This can be done by
opening a file in read mode using file pointer. Read the file line by line. Split a line at a time and store in
an array. Iterate through the array and find the frequency of each word and compare the frequency with
maxcount. If frequency is greater than maxcount then store the frequency in maxcount and
corresponding word that in variable word. The content of data.txt file used in the program is shown
below.

data.txt

A computer program is a collection of instructions that performs specific task when executed by a
computer.

Computer requires programs to function.

Computer program is usually written by a computer programmer in programming language.

A collection of computer programs, libraries, and related data are referred to as software.

Computer programs may be categorized along functional lines, such as application software and system
software.

Algorithm
• STEP 1: START
• STEP 2: DEFINE String line, word = ""
• STEP 3: SET count =0, maxCount =0
• STEP 4: DEFINE ArrayList<String> words
• STEP 5: USE File Reader to open file in read mode.
• STEP 6: READ line from file
• STEP 7: By looping, CONVERT each line into lower case.
• STEP 8: REMOVE the punctuation marks.
• STEP 9: SPLIT the lines and STORE in array string[].
• STEP 10: ADD all words generated in previous step into words.
• STEP 11: SET i=0.REPEAT STEP 12 to STEP 17 UNTIL i<words.size()
• STEP 12: SET count =1
• STEP 13: SET j=i+1.REPEAT STEP 14 to 15 STEP UNTIL j<words.size()
• STEP 14: IF(words.get(i).equals(words.get(j))) then count = count+1.
• STEP 15: j = j+1
• STEP 16: IF count>maxCount
then
maxCount = count
word =words.get(i)
• STEP 17: i=i+1
• STEP 18: PRINT word
• STEP 19: END

Program:

import java.io.BufferedReader;

import java.io.FileReader;

import java.util.ArrayList;

public class MostRepeatedWord {

public static void main(String[] args) throws Exception {

String line, word = "";

int count = 0, maxCount = 0;

ArrayList<String> words = new ArrayList<String>();

//Opens file in read mode

FileReader file = new FileReader("data.txt ");

BufferedReader br = new BufferedReader(file);

//Reads each line

while((line = br.readLine()) != null) {

String string[] = line.toLowerCase().split("([,.\\s]+) ");

//Adding all words generated in previous step into words


for(String s : string){

words.add(s);

//Determine the most repeated word in a file

for(int i = 0; i < words.size(); i++){

count = 1;

//Count each word in the file and store it in variable count

for(int j = i+1; j < words.size(); j++){

if(words.get(i).equals(words.get(j))){

count++;

//If maxCount is less than count then store value of count in maxCount

//and corresponding word to variable word

if(count > maxCount){

maxCount = count;

word = words.get(i);

System.out.println("Most repeated word: " + word);

br.close();
}

Output:

Most repeated word: computer

How to Check if Given Number is Prime in Java -


With Example
Hello guys, today, we are going to discuss one of the most common programming exercises for beginners is,
write a program to check if a given number is prime or not? There are many ways to check if a number is
prime or not, but the most common of them is the trial division, which is what we will see in this tutorial. In my
opinion, these kinds of programs are their first steps towards algorithmic understanding. You first come up with a
solution, which is driven by the fact that prime numbers are natural numbers, that are not divisible by any positive
number other than 1 and themselves. Then, you write a for loop to check every number, starting from 1 to a given
number, to see if the given number is divisible by any positive number or not. This leads you to the solution.

Then you find some more the fact that there is no need to check till N-1, where N is the number we are checking
for primeness, and checking till the square root of N is enough. This reduces a lot of time, especially while
checking a large number is prime or not.

Further, you come to know that if it's not divisible by 2, then there is no need to checking for any other even
number, and you increment the counter by 2 instead of 1. So in a way, you learn how to optimize your solution by
taking advantage of facts available.

After this, you can try something like the Fibonacci series or maybe finding a factorial of a number in Java to do
some more practice on programming. This will not only teach you language basics like loops, control
statements like if-else, use of arithmetic, and relational operator but also helps to develop programming logic.

By the way, you can even take this problem of checking if a number is prime or not, to the next level, by trying to
implement different algorithms for finding primes like the sieve of Atkin or sieve of Eratosthenes. In fact, in
programming challenges, you often need to build your prime number cache up-to a specific number to progress
further in finding a solution.

How to Remove Duplicates from Array Without Using


Java Collection API
This is a coding question recently asked to one of my readers in a Java Technical interview. Question was to
remove duplicates from an integer array without using any collection API classes like Set or
LinkedHashSet, which can make this task trivial. In general, if you need to do this for any project work, I
suggest better using the Set interface, particularly LinkedHashSet, because that also keep the order on which
elements are inserted into Set. Only for technical interview perspective, you need to do this using either loops or
recursion, depending upon what is your strongest area. In this article, I am sharing a naive solution, which has
lots of limitation to be considered as production quality code, It's not the best solution but still a solution.

The main problem, while dealing with an array is not finding duplicates, it's about removing them. Since an array
is a static, fixed-length data structure, you can not change its length. This means, deleting an element from an
array requires creating a new array and copying content into that array.

If your input array contains lots of duplicates then this may result in lots of temporary arrays. It also increases the
cost of copying content, which can be very bad. Given this restriction, you need to come out with a strategy to
minimize both memory and CPU requirements.

Before going for a programming/coding interview, It's absolutely necessary to do as much practice in data
structure and algorithm as possible to take advantage of all the knowledge available. You can also join a
comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using
Java on Udemy to fill the gaps in your understanding.

Java Program to remove duplicates from integer array without Collection

Now, let's see our Java solution for removing duplicates from integer array:

import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Java program to remove duplicates from this array. You don't
* need to physically delete duplicate elements, replacing with null, or
* empty or default value is ok.
*
* @author http://javarevisited.blogspot.com
*/
public class TechnicalInterviewTest {

private static final Logger logger =


LoggerFactory.getLogger(TechnicalInterviewTest.class);

public static void main(String args[]) {

int[][] test = new int[][]{


{1, 1, 2, 2, 3, 4, 5},
{1, 1, 1, 1, 1, 1, 1},
{1, 2, 3, 4, 5, 6, 7},
{1, 2, 1, 1, 1, 1, 1},};

for (int[] input : test) {


System.out.println("Array with Duplicates : " +
Arrays.toString(input));
System.out.println("After removing duplicates : " +
Arrays.toString(removeDuplicates(input)));
}
}

/*
* Method to remove duplicates from array in Java, without using
* Collection classes e.g. Set or ArrayList. Algorithm for this
* method is simple, it first sort the array and then compare adjacent
* objects, leaving out duplicates, which is already in the result.
*/
public static int[] removeDuplicates(int[] numbersWithDuplicates) {

// Sorting array to bring duplicates together


Arrays.sort(numbersWithDuplicates);

int[] result = new int[numbersWithDuplicates.length];


int previous = numbersWithDuplicates[0];
result[0] = previous;

for (int i = 1; i < numbersWithDuplicates.length; i++) {


int ch = numbersWithDuplicates[i];

if (previous != ch) {
result[i] = ch;
}
previous = ch;
}
return result;

}
}

Output :
Array with Duplicates : [1, 1, 2, 2, 3, 4, 5]
After removing duplicates : [1, 0, 2, 0, 3, 4, 5]
Array with Duplicates : [1, 1, 1, 1, 1, 1, 1]
After removing duplicates : [1, 0, 0, 0, 0, 0, 0]
Array with Duplicates : [1, 2, 3, 4, 5, 6, 7]
After removing duplicates : [1, 2, 3, 4, 5, 6, 7]
Array with Duplicates : [1, 2, 1, 1, 1, 1, 1]
After removing duplicates : [1, 0, 0, 0, 0, 0, 2]

That's it about how to remove duplicates from an array in Java without using Collection class. As I said
before, this solution is not perfect and has some serious limitation, which is an exercise for you to find out. One
hint I can give is that array itself can contain default value as duplicates e.g. 0 for int, even if you use any Magic
number e.g. Integer.MAX_VALUE, you can not be certain that they will not be part of the input.

Regarding removing duplicate permanently from result array, one approach could be to count a number of
duplicates and then create an array of right size i.e. length - duplicates, and then copying content from
intermediate result array to final array, leaving out elements which are marked duplicate.

Find the missing number in an Array in


Java with Examples
One of the most frequently asked basic java coding question is to find the missing number in an array of
integers of length n-1 containing integer values from 1 to n.The given Array does not contain duplicates or
occurrence of each integer value is only once.

I have faced this question for the java developer position twice. Make sure this question in your to do list before
appearing for the interview.

There are follow up questions like

• how to find the missing number in a given unsorted array with duplicates.If you solve it, then another
follow up question is
• find the multiple missing numbers in a given unsorted array with duplicates.

Examples :
int[] input = {10,9,6,7,4,3,5,1,2}
Output :
Missing number in an array : 8

int[] input = {6,1,4,2,3}

Output :
Missing number in an array : 5

Solution

1. First step, we will find the sum of n numbers using math formula n*(n+1)/2

2. Second step, we will find the sum of all numbers in the given input array.

3. Using subtraction, we will find the missing number

missingNumber = (Sum of 1 to n numbers) - (Sum of numbers in the given input array)

Java Program to find the missing number in an Array, Duplicates not allowed :
Below is the java program to find the missing number in an Array, Duplicates are not allowed.

/* Java Program to find the


missing number in a given unsorted array
duplicates are not allowed */

public class JavaHungry {

public static void main(String args[]) {

// Given input Array from 1 to n


int[] input = {10,9,6,7,4,3,5,1,2};

// Calculate n value
//(we add 1 because one element is already missed)
int n = input.length + 1;

// Calculate Sum of N Number


// using Math formula n(n+1)/2
int sumOfNNumbers = sumOfAllNNumbers(n);

// Calculate Sum of all numbers in input array


int sumOfInputArray = sumOfInputArrayNumbers(input);

// Calculate missing number


// using subtraction
int missingNumber = sumOfNNumbers - sumOfInputArray;

// Print the Missing number


System.out.println("Missing number in an array is : "
+ missingNumber);
}

public static int sumOfAllNNumbers(int n){


int sum = (n*(n+1))/2;
return sum;
}

public static int sumOfInputArrayNumbers(int[] input){


int sum = 0;
for(int i=0; i < input.length ;i++){
sum = sum + input[i];
}
return sum;
}
}

Output :
Missing number in an array is : 8

Follow up question:
How to find the missing number in an unsorted Array with duplicate elements.

Examples :
Integer[] input = {10,9,6,7,7,9,10,3,4,3,5,1,2}

Output :
Missing number in an array : 8

Integer[] input = {6,1,4,2,3,3,1,6}

Output :
Missing number in an array : 5

Solution :

1. First Step, convert the given input Array to List and pass this List to the HashSet constructor. Using this step I
remove the duplicate elements from the List. Rest is same as the previous question.

Java Program to find the missing number in an unsorted Array with duplicates allowed :
Below is the java program to find the missing number in an unsorted Array with Duplicates allowed.
/* Java Program to find the
missing number in a given unsorted array
with duplicates allowed */

import java.util.*;

public class JavaHungry {

public static void main(String args[]) {

// Given input Array from 1 to n


Integer[] input = {10,9,6,7,7,9,10,3,4,3,5,1,2};

//Convert input Array to List


List arrList = Arrays.asList(input);

//Remove Duplicates by passing list


//to the HashSet Constructor
HashSet<Integer> hsobj = new HashSet(arrList);

// Calculate n value
int n = hsobj.size() + 1;

// Calculate Sum of N Number


// using Math formula n(n+1)/2
int sumOfNNumbers = sumOfAllNNumbers(n);

// Calculate Sum of all numbers in HashSet object


int sumOfHashSetNumbers = sumOfHashSetNumbers(hsobj);

// Calculate missing number


// using subtraction
int missingNumber = sumOfNNumbers - sumOfHashSetNumbers;

// Print the Missing number


System.out.println("Missing number in an array is : "
+ missingNumber);
}

public static int sumOfAllNNumbers(int n){


int sum = (n*(n+1))/2;
return sum;
}
public static int sumOfHashSetNumbers(HashSet<Integer> hsobj){
int sum = 0;
for(Integer obj : hsobj){
sum = sum + obj;
}
return sum;
}
}

Output :
Missing number in an array is : 8

How to find the multiple missing numbers in an


unsorted Array with duplicate elements.
Examples :
int[] input = {10,9,6,7,7,5,1,2,2}

Output :
Missing numbers in an array are : 3 4 8

int[] input = {6,1,3,3,1,6,8}

Output :
Missing numbers in an array are : 2 4 5 7

Solution:

1. Create another Array named as copyArray of the given input Array. Mark all the indexes present in the
copyArray to 1 for the corresponding value in input Array.

2. Calculate the max value in the given input Array.We will iterate copyArray till max value while printing the
missing numbers.
3. Iterate through the copyArray and print all those values which are 0. Hence, the missing numbers.

Java Program to find the multiple missing numbers in an unsorted Array with
duplicates allowed:
/* Java Program to find multiple
missing numbers in a given unsorted
array with duplicates allowed */

import java.util.*;

public class JavaHungry {

public static void main(String args[]) {

// Given input Array from 1 to n


Integer[] input = {6,1,3,3,1,6,8};

// Calculate the max value in given Array


int max = calculateArrayMaxValue(input);

//Create another Array of same size


//By default all values initialize to 0
// default value of int
int[] copyArray = new int[100];

//Iterate thorugh the input array


//Mark all present numbers in copyArray
for(int i : input) {
copyArray[i] = 1;
}

// Print the missing numbers


System.out.print("Missing numbers in an array are : ");

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


if(copyArray[i]==0)
System.out.print(i + " ");
}
}

public static int calculateArrayMaxValue(Integer[] input) {

// Initialize maximum element


int max = input[0];
// Iterating array elements from second and
// compare every element with current max
for (int i = 1; i < input.length; i++)
if (input[i] > max)
max = input[i];

return max;

}
}

Output :
Missing numbers in an array are : 2 4 5 7

How to Find all Pairs in Array of Integers Whose sum


is Equal to a Given Number - Java Solution
Practicing coding problems are very important to do well in any programming interview. You should at your best
on data-structures like an array, linked list, and string to clear any programming interview, and believe me, you
can not do this in one day or one week. It's rather a long process of learning through coding, and that's where
these small coding problems help. Today, we are going to look at another interesting programming question from
the array; write a program to find all pairs of integers whose sum is equal to a given number. For example, if the
input integer array is {2, 6, 3, 9, 11} and given sum is 9, the output should be {6,3}.

In a programming interview, many things matter apart from the correct solution. For example, the first thing the
Interviewer looks at is whether a candidate can ask the right questions or not. So before jumping straight to
coding, spare a second or two to think about the problem and clear any doubt you may have.

For example, you can ask the following questions based upon problem statement given above :

• Does the array contain only positive or negative numbers?


• What if the same pair repeats twice, should we print it every time?
• Is the reverse of pair is acceptable e.g. can we print both (4,1) and (1,4) if the given sum is 5.
• Do we need to print only a distinct pair? does (3, 3) is a valid pair forgiven sum of 6?
• How big the array is?

Many programmers afraid to ask questions instead they like to assume about it, but during coding interview
IMHO it's always better to ask questions. First, it shows that you have not mugged the answer and second it
demonstrates that you have the ability to think through a problem, which is a very important quality of any
professional programmer.

Now let's go back to question, for simplicity we can assume that we just need to print a pair of integers once or
twice depending upon their occurrence, but pair has to be distinct, (2,2) or (3, 3) is not valid pair.

3 Solutions to Find Pair Of Integers in Array whose Sum is Given Number

The first solution which comes in my mind is our friend brute-force, naive but genuine. You take one number
from the array and then loop through array and output pairs which is equal to given sum. You do this for all
numbers in first array, as shown in the following Java program :

1. Brute Force Solution

import java.util.Arrays;

/**
* Java Program to find pairs on integer array whose sum is equal to k
*
* @author WINDOWS 8
*/
public class ProblemInArray{

public static void main(String args[]) {


int[] numbers = { 2, 4, 3, 5, 7, 8, 9 };
int[] numbersWithDuplicates = { 2, 4, 3, 5, 6, -2, 4, 7, 8, 9 };
prettyPrint(numbers, 7);
prettyPrint(numbersWithDuplicates, 7);
}

/**
* Prints all pair of integer values from given array whose sum is
* is equal to given number.
* complexity of this solution is O(n^2)
*/
public static void printPairs(int[] array, int sum) {

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


int first = array[i];
for (int j = i + 1; j < array.length; j++) {
int second = array[j];

if ((first + second) == sum) {


System.out.printf("(%d, %d) %n", first, second);
}
}

}
}
/**
* Utility method to print input and output for better explanation.
*/
public static void prettyPrint(int[] givenArray, int givenSum){
System.out.println("Given array : " + Arrays.toString(givenArray));
System.out.println("Given sum : " + givenSum);
System.out.println("Integer numbers, whose sum is equal to value : "
+ givenSum);
printPairs(givenArray, givenSum);
}

Output:
Given sum : 7
Integer numbers, whose sum is equal to value : 7
(2, 5)
(4, 3)
Given array : [2, 4, 3, 5, 6, -2, 4, 7, 8, 9]
Given sum : 7
Integer numbers, whose sum is equal to value : 7
(2, 5)
(4, 3)
(3, 4)
(-2, 9)
This solution is correct but its time complexity is very hight, O(n^2), which means the Interviewer will surely
ask you to improve your answer and come up with a solution whose complexity is either O(1), O(n) or
O(nLog(n)). So let's dig deeper to improve this answer. In order to find two numbers in an array whose sum
equals a given value, we probably don't need to compare each number with other.

What we can do here is to store all numbers in a hashtable and just check if it contains second value in a pair. For
example, if a given sum is 4 and one number in pair is 3, then other must be 1 or -7. Do you remember the first
question we asked, if array only contains positive numbers then we don't need to check for negative values in
Map. How is this solution better than previous one? It would require less comparisons.

Only N to iterate through array and insert values in a Set because add() and contains() both O(1) operation
in hash table. So total complexity of the solution would be O(N). Here is a Java program which find the pair of
values in the array whose sum is equal to k using Hashtable or Set. In this program we have also written a utility
method to generate random numbers in a given range in Java. You can use this method for testing with random
inputs.

By the way, random numbers are only good for demonstration, don't use them in your unit test. One more good
thing you can learn from printPairsUsingSet() method is pre validation, checking if inputs are valid to
proceed further.

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

/**
* Java Program to find two elements in an array that sum to k.
*
* @author WINDOWS 8
*/
public class ArraySumUsingSet {

public static void main(String args[]) {


prettyPrint(getRandomArray(9), 11);
prettyPrint(getRandomArray(10), 12);
}

/**
* Given an array of integers finds two elements in the array
* whose sum is equal to n.
* @param numbers
* @param n
*/
public static void printPairsUsingSet(int[] numbers, int n){
if(numbers.length < 2){
return;
}
Set set = new HashSet(numbers.length);

for(int value : numbers){


int target = n - value;

// if target number is not in set then add


if(!set.contains(target)){
set.add(value);
}else {
System.out.printf("(%d, %d) %n", value, target);
}
}
}

/*
* Utility method to find two elements in an array that sum to k.
*/
public static void prettyPrint(int[] random, int k){
System.out.println("Random Integer array : " + Arrays.toString(random));
System.out.println("Sum : " + k);
System.out.println("pair of numbers from an array whose sum equals "
+ k);
printPairsUsingSet(random, k);
}

/**
* Utility method to return random array of Integers in a range of 0 to 15
*/
public static int[] getRandomArray(int length){
int[] randoms = new int[length];
for(int i=0; i<length; i++){
randoms[i] = (int) (Math.random()*15);
}
return randoms;
}

Output:
Random Integer array : [0, 14, 0, 4, 7, 8, 3, 5, 7]
Sum : 11
pair of numbers from an array whose sum equals 11
(7, 4)
(3, 8)
(7, 4)
Random Integer array : [10, 9, 5, 9, 0, 10, 2, 10, 1, 9]
Sum : 12
pair of numbers from an array whose sum equals 12
(2, 10)

One more thing, here we are using HashSet but since HashSet in Java internally uses HashMap, it would not
make any difference if use either of those data structure.By the this solution has few constraints, first it would
need additional space of order O(n) to store numbers in Hashtable or Set, so you need additional space which
could be problem if array is very large (remember the question we asked before writing solution).

For a large array, you need a solution which doesn't require additional space, also known as in-place solution. If
interviewer will ask you how do you find if two values in an array sum to a given value without any additional
space, first solution will also not work because it's complexity is too high and it would too long to sort a large
array. A solution with complexity e.g. O(n), O(logN) or O(NLongN) should work though.

A more efficient in-place solution would be to sort the array and use two pointers to scan through array from both
direction i.e. beginning and end. If sum of both the values are equal to given number then we output the pair and
advance them. If the sum of two numbers is less than k then we increase the left pointer, else if the sum is greater
than k we decrement the right pointer, until both pointers meet at some part of the array.

The complexity of this solution would be O(NlogN) due to sorting. Remember to use a in-place sorting
algorithm like quicksort to sort the array as we don't have additional space. Thankfully, Arrays.sort()
method uses a two pivot quicksort algorithm to sort array of primitives.

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

/**
* Java Program to find all pairs on integer array whose sum is equal to k
*
* @author WINDOWS 7
*/
public class PrintArrayPairs {

public static void main(String args[]) {


prettyPrint( new int[]{ 12, 14, 17, 15, 19, 20, -11}, 9);
prettyPrint( new int[]{ 2, 4, 7, 5, 9, 10, -1}, 9);
}

/**
* Given a number finds two numbers from an array so that
* the sum is equal to that number k.
* @param numbers
* @param k
*/
public static void printPairsUsingTwoPointers(int[] numbers, int k){
if(numbers.length < 2){
return;
}
Arrays.sort(numbers);

int left = 0; int right = numbers.length -1;


while(left < right){
int sum = numbers[left] + numbers[right];
if(sum == k){
System.out.printf("(%d, %d) %n", numbers[left],
numbers[right]);
left = left + 1;
right = right -1;

}else if(sum < k){


left = left +1;

}else if (sum > k) {


right = right -1;
}
}

/*
* Utility method to print two elements in an array that sum to k.
*/
public static void prettyPrint(int[] random, int k){
System.out.println("input int array : " + Arrays.toString(random));
System.out.println("All pairs in an array of integers
whose sum is equal to a given value " + k);
printPairsUsingTwoPointers(random, k);
}

Output :
input int array : [12, 14, 17, 15, 19, 20, -11]
All pairs in an array of integers whose sum is equal to a given value 9
(-11, 20)
input int array : [2, 4, 7, 5, 9, 10, -1]
All pairs in an array of integers whose sum is equal to a given value 9
(-1, 10)
(2, 7)
(4, 5)

That' all on this array based interview question to find all pairs in an array of integers whose sum is equal to a
given integer. We have seen three ways to solve this problem starting from simplest brute-force solution to
acceptable O(N) with additional space and O(NLogN) in-place. If anyone like to do some more practice, I
would suggest writing JUnit test cases for this problem, given set of constraints that only unique pair needs to be
printed even if array contains duplicated and find bugs on these solution.
Alternatively, you can also try to solve it's cousin question, given an array of integers check whether there are 3
numbers that sum up to 0 or given number. Remember more fun is in journey than reaching the destination :)

Exercises :
1) Write JUnit tests for this problem and check if each of this solution passes those tests.
2) Come up with a better solution in terms of time and space complexity?
3) Find boundary conditions on which these solution breaks.

Difference Between Linked List and Array Data


Structure in Java Programming
Array and linked lists are two fundamental data structures in the programming world. Almost all
programs use Array in some form or other, which makes it increasingly important to learn array and
linked list. The difference between the linked list and array data structure is also a popular data
structure question, frequently asked in the various programming job interviews. This makes it even
more important to learn and understand the difference between an array and a linked list. Well, there
are a lot of differences between these two starting from how they store data, to how you retrieve data
from them.

The main difference comes from the fact that array elements are stored in a contiguous memory
location, which makes it easy to retrieve them in quick time, while linked list elements are scattered
throughout memory, where one element knows the address of other, it makes it hard to retrieve an
element from a linked list in quick time.

Some of the differences which we saw in ArrayList vs LinkedList also applicable at the data structure
level, because ArrayList is backed by an array, and LinkedList is internally backed by a double
linked list in Java.

In this tutorial, we will learn the differences between these two fundamental data structures in more
detail. Once you know the difference, you can make a concise choice of which data structure suits your
need better. Since both of them offers a distinctive advantage over others, in terms of speed and
flexibility, You can make an informed choice based upon your need.

Also, basic knowledge of essential data structure is also very important and that's why I suggest all Java
programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms:
Deep Dive Using Java on Udemy to fill the gaps in your understanding.

Array vs linked list in Java


Here is my list of differences between array and linked list. Though data structure concept are
independent of any programming language and more or less applicable in all programming language
including C and C++, I have explained differences in Java's context.

1. Random Access vs Sequential Access


The first and major difference between the linked list and array data structure is that the former doesn't
support random access, while later supports random access. a linked list is sequential, in order to
retrieve an element, you need to traverse till that, while if you know the index, you can retrieve an
element from array very quickly because it doesn't involved traversal.

2. Contiguous vs Scattered Memory


The second major difference between array and linked-list data structure is that, array needs
contiguous memory allocation, which may result in java.lang.OutOfMemoryError: Java Heap Space if
there is not enough contiguous ( a big chunk) of memory in Java Heap. On the other hand, linked list is
distributed data structure, it's element are scattered over heap and doesn't need a contiguous memory
allocation. This makes linked list ideal, if you have scattered memory.

3. Fixed length vs Flexible growth


The third major difference is fixed length, array is a fixed length data structure, you provide length or
size of array at the time of creation, later you can not modify that size. On the other hand, linked list is
dynamic data structure, it can grow and doesn't required size to be specified at the time of creation,
because each node keep tracks of other.

4. Ease of Insertion and Deletion


It's easy to insert and delete elements from linked list than array, especially inserting element at
beginning of linked list, and deleting element from end of linked list is O(1) operation. On the other hand
array is fixed length data structure, so memory is allocated during initialization, and doesn't really
change due to addition and removal of elements. Though you can set a particular index null, to cut the
reference count of that object.

5. Usage in derived Data Structure


The array is ideal for implementing fast caches e.g. HashMap or Hashtable, which requires constant
time retrieval e.g. Map data structure provides O(1) performance for get(Key key) operation, while
linked list-based structure provides liner performance i.e. O(n) for retrieval operation, where n is the
number of elements in a linked list.

6. Types
Array can be one or multi-dimensional, while linked list can be singly, doubly or circular linked list. Two-
dimensional array are most common in multi-dimensional and used to represent matrix in Java.

You can use two-dimensional array to represent a plain of x,y coordinates, frequently used in Game
programming. Java programming language provides support for creating array at syntax level, it
supports both single and multidimensional array. Java API also provides a class called
java.util.LinkedList, which is an implementation of a doubly-linked list data structure.
That's all on my list of differences between array and linked list data structure. I strongly suggest
getting a good hold of these data structures, especially linked list, which is very popular among data
structure interview questions. Questions like appending elements into linked list, deleting elements,
reversing linked list are quite common in various programming jobs. At very least, knowledge of
fundamental data structure is essential to do well in programming jobs.

How to Check or Detect Duplicate


Elements in Array in Java
Detecting duplicate elements in Java array is another programming interview question I like. There could be a
lot of ways you can check if your array contains duplicate elements or not and sometimes you discover a
unique way of checking duplicates by asking this question on Java interview. The beauty of this question is that it
has an endless number of follow-up question so if interviewee gets through this question you can ask to him about
time complexity and space or to improve his algorithm to make it fast .you can even ask to find those duplicate
elements in Array which even can go from one duplicate to many repeating elements in Array. As I said you can
really test programming skills around an array of a Java programmer.

Checking Array for duplicate elements Java


In this Java tutorial, we will see a couple of ways to find if an array contains duplicates or not in Java. We will use
the unique property of Java collection class Set which doesn’t allow duplicates to check java array for duplicate
elements. Here are five ways we can check if an array has duplicates or not:

1) brute force method which compares each element of Array to all other elements and returns true if it founds
duplicates. Though this is not an efficient choice it is the one which first comes to mind.

2) Another quick way of checking if a Java array contains duplicates or not is to convert that array into Set.
Since Set doesn’t allow duplicates size of the corresponding Set will be smaller than the original Array if Array
contains duplicates otherwise the size of both Array and Set will be the same.

3) One more way to detect duplication in java array is adding every element of the array into HashSet which is a
Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be
added, it can be used to find out if the array contains duplicates in Java or not.
In next section, we will complete code example of all three ways of duplicate detection on Array in java.
Remember this discussion is just confirming whether an array contains duplicate or not , it's not finding out actual
duplicate elements from Array though you can easily extend example Java program to accomplish that task based
on your requirement.

Code Example of checking duplicate on Array in Java


Here is complete code sample of all above methods to check if your array contains duplicates or not.

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CheckDuplicatesInJavaArray {

public static void main(String args[]) {

String[] withDuplicates = new String[] {"one","two","three","one"};


String[] withoutDuplicates = new String[] {"one","two","three"};

System.out.println("Checking array with duplicate using brute force:


" + bruteforce(withDuplicates));
System.out.println("Checking array without any duplicate using brute
force: " + bruteforce(withoutDuplicates));

System.out.println("Checking array with duplicate using Set and


List: " + checkDuplicateUsingSet(withDuplicates));
System.out.println("Checking array without any duplicate using Set
and List: " + checkDuplicateUsingSet(withoutDuplicates));

System.out.println("Checking array with duplicate using Set and


List: " + checkDuplicateUsingAdd(withDuplicates));
System.out.println("Checking array without any duplicate using Set
and List: " + checkDuplicateUsingAdd(withoutDuplicates));

/*
* brute force way of checking if array contains duplicates in Java
* comparing each element to all other elements of array
* complexity on order of O(n^2) not advised in production
*/
public static boolean bruteforce(String[] input) {
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length; j++) {
if (input[i].equals(input[j]) && i != j) {
return true;
}
}
}
return false;
}
/*
* detect duplicate in array by comparing size of List and Set
* since Set doesn't contain duplicate, size must be less for an array
which contains duplicates
*/
public static boolean checkDuplicateUsingSet(String[] input){
List inputList = Arrays.asList(input);
Set inputSet = new HashSet(inputList);
if(inputSet.size()< inputList.size())
return true;
}
return false;
}

/*
* Since Set doesn't allow duplicates add() return false
* if we try to add duplicates into Set and this property
* can be used to check if array contains duplicates in Java
*/
public static boolean checkDuplicateUsingAdd(String[] input) {
Set tempSet = new HashSet();
for (String str : input) {
if (!tempSet.add(str)) {
return true;
}
}
return false;
}
}

Output:
Checking array with duplicate using brute force: true
Checking array without any duplicate using brute force: false
Checking array with duplicate using Set and List: true
Checking array without any duplicate using Set and List: false
Checking array with duplicate using Set and List: true
Checking array without any duplicate using Set and List: false
That’s all on how to check if an Array contains duplicate or not in Java. You see we have used Java
Collection API in two of our example, there can be other pure programming solution as well. You may be asked
to detect duplicates without using Java API in the real interview. Let us know if you come across some other good
way of checking duplicates in an array without using Java API.

Union and Intersection of two sorted arrays


Given two sorted arrays, find their union and intersection.
Example:

Input : arr1[] = {1, 3, 4, 5, 7}


arr2[] = {2, 3, 5, 6}
Output : Union : {1, 2, 3, 4, 5, 6, 7}
Intersection : {3, 5}

Input : arr1[] = {2, 5, 6}


arr2[] = {4, 6, 8, 10}
Output : Union : {2, 4, 5, 6, 8, 10}
Intersection : {6}

Union of arrays arr1[] and arr2[]

To find union of two sorted arrays, follow the following merge procedure :

1) Use two index variables i and j, initial values i = 0, j = 0


2) If arr1[i] is smaller than arr2[j] then print arr1[i] and increment i.
3) If arr1[i] is greater than arr2[j] then print arr2[j] and increment j.
4) If both are same then print any of them and increment both i and j.
5) Print remaining elements of the larger array.

Below is the implementation of the above approach :

// Java program to find union of


// two sorted arrays
class FindUnion {
/* Function prints union of arr1[] and arr2[]
m is the number of elements in arr1[]
n is the number of elements in arr2[] */
static int printUnion(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while (i < m && j < n) {
if (arr1[i] < arr2[j])
System.out.print(arr1[i++] + " ");
else if (arr2[j] < arr1[i])
System.out.print(arr2[j++] + " ");
else {
System.out.print(arr2[j++] + " ");
i++;
}
}

/* Print remaining elements of


the larger array */
while (i < m)
System.out.print(arr1[i++] + " ");
while (j < n)
System.out.print(arr2[j++] + " ");

return 0;
}

public static void main(String args[])


{
int arr1[] = { 1, 2, 4, 5, 6 };
int arr2[] = { 2, 3, 5, 7 };
int m = arr1.length;
int n = arr2.length;
printUnion(arr1, arr2, m, n);
}
}

Output:

1 2 3 4 5 6 7

Time Complexity : O(m + n)


Handling duplicates in any of the array : Above code does not handle duplicates in any of the array.
To handle the duplicates, just check for every element whether adjacent elements are equal.
Below is the implementation of this approach.

// Java program to find union of two


// sorted arrays (Handling Duplicates)
class FindUnion {

static void UnionArray(int arr1[], int arr2[])


{
// Taking max element present in either array
int m = arr1[arr1.length - 1];
int n = arr2[arr2.length - 1];

int ans = 0;

if (m > n) {
ans = m;
}
else
ans = n;

// Finding elements from 1st array


// (non duplicates only). Using
// another array for storing union
// elements of both arrays
// Assuming max element present
// in array is not more than 10^7
int newtable[] = new int[ans + 1];

// First element is always


// present in final answer
System.out.print(arr1[0] + " ");

// Incrementing the First element's count


// in it's corresponding index in newtable
++newtable[arr1[0]];

// Starting traversing the first


// array from 1st index till last
for (int i = 1; i < arr1.length; i++) {
// Checking whether current element
// is not equal to it's previous element
if (arr1[i] != arr1[i - 1]) {
System.out.print(arr1[i] + " ");
++newtable[arr1[i]];
}
}

// Finding only non common


// elements from 2nd array
for (int j = 0; j < arr2.length; j++) {
// By checking whether it's already
// present in newtable or not
if (newtable[arr2[j]] == 0) {
System.out.print(arr2[j] + " ");
++newtable[arr2[j]];
}
}
}
// Driver Code
public static void main(String args[])
{
int arr1[] = { 1, 2, 2, 2, 3 };
int arr2[] = { 2, 3, 4, 5 };

UnionArray(arr1, arr2);
}
}

Thanks to Rajat Rawat for suggesting this solution.

Intersection of arrays arr1[] and arr2[]


To find intersection of 2 sorted arrays, follow the below approach :

1) Use two index variables i and j, initial values i = 0, j = 0


2) If arr1[i] is smaller than arr2[j] then increment i.
3) If arr1[i] is greater than arr2[j] then increment j.
4) If both are same then print any of them and increment both i and j.

Below is the implementation of the above approach :

// C++ program to find intersection of


// two sorted arrays
#include <bits/stdc++.h>
using namespace std;

/* Function prints Intersection of arr1[] and arr2[]


m is the number of elements in arr1[]
n is the number of elements in arr2[] */
int printIntersection(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while (i < m && j < n) {
if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr1[i])
j++;
else /* if arr1[i] == arr2[j] */
{
cout << arr2[j] << " ";
i++;
j++;
}
}
}
/* Driver program to test above function */
int main()
{
int arr1[] = { 1, 2, 4, 5, 6 };
int arr2[] = { 2, 3, 5, 7 };

int m = sizeof(arr1) / sizeof(arr1[0]);


int n = sizeof(arr2) / sizeof(arr2[0]);

// Function calling
printIntersection(arr1, arr2, m, n);

return 0;
}

Output:

2 5

Time Complexity : O(m + n)

Given two unsorted arrays, find all pairs whose sum is x


Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum
is equal to X.

Examples:

Input : arr1[] = {-1, -2, 4, -6, 5, 7}


arr2[] = {6, 3, 4, 0}
x = 8
Output : 4 4
5 3

Input : arr1[] = {1, 2, 4, 5, 7}


arr2[] = {5, 6, 3, 4, 8}
x = 9
Output : 1 8
4 5
5 4

// Java program to find all pairs in both arrays


// whose sum is equal to given value x
import java.io.*;
class GFG {

// Function to print all pairs in both arrays


// whose sum is equal to given value x
static void findPairs(int arr1[], int arr2[], int n,int m, int x)
{
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (arr1[i] + arr2[j] == x)
System.out.println(arr1[i] + " "
+ arr2[j]);
}

// Driver code
public static void main(String[] args)
{
int arr1[] = { 1, 2, 3, 7, 5, 4 };
int arr2[] = { 0, 7, 4, 3, 2, 1 };
int x = 8;
findPairs(arr1, arr2, arr1.length, arr2.length, x);
}
}

// This code is contributed


// by sunnysingh

Output:
1 7
7 1
5 3
4 4

Time Complexity : O(n^2)


Auxiliary Space : O(1)

Smallest Difference pair of values between two unsorted Arrays


Given two arrays of integers, compute the pair of values (one value in each array) with the smallest
(non-negative) difference. Return the difference.

Examples :

Input : A[] = {l, 3, 15, 11, 2}


B[] = {23, 127, 235, 19, 8}
Output : 3
That is, the pair (11, 8)

Input : A[] = {l0, 5, 40}


B[] = {50, 90, 80}
Output : 10
That is, the pair (40, 50)
A simple solution is to Brute Force using two loops with Time Complexity O(n2).

A better solution is to sort the arrays. Once the arrays are sorted, we can find the minimum difference
by iterating through the arrays using the approach discussed in below post.

Find the closest pair from two sorted arrays


Consider the following two arrays:
A: {l, 2, 11, 15}
B: {4, 12, 19, 23, 127, 235}

1. Suppose a pointer a points to the beginning of A and a pointer b points to the beginning of B.
The current difference between a and bis 3. Store this as the min.
2. How can we (potentially) make this difference smaller? Well, the value at bis bigger than the
value at a, so moving b will only make the difference larger. Therefore, we want to move a.
3. Now a points to 2 and b (still) points to 4. This difference is 2, so we should update min. Move a,
since it is smaller.
4. Now a points to 11 and b points to 4. Move b.
5. Now a points to 11 and b points to 12. Update min to 1. Move b. And so on.

Below is the implementation of the idea.

// Java Code to find Smallest


// Difference between two Arrays
import java.util.*;

class GFG
{

// function to calculate Small


// result between two arrays
static int findSmallestDifference(int A[], int B[],
int m, int n)
{
// Sort both arrays
// using sort function
Arrays.sort(A);
Arrays.sort(B);

int a = 0, b = 0;

// Initialize result as max value


int result = Integer.MAX_VALUE;

// Scan Both Arrays upto


// sizeof of the Arrays
while (a < m && b < n)
{
if (Math.abs(A[a] - B[b]) < result)
result = Math.abs(A[a] - B[b]);

// Move Smaller Value


if (A[a] < B[b])
a++;

else
b++;
}

// return final sma result


return result;
}

// Driver Code
public static void main(String[] args)
{
// Input given array A
int A[] = {1, 2, 11, 5};

// Input given array B


int B[] = {4, 12, 19, 23, 127, 235};

// Calculate size of Both arrays


int m = A.length;
int n = B.length;

// Call function to
// print smallest result
System.out.println(findSmallestDifference
(A, B, m, n));

}
}
// This code is contributed
// by Arnav Kr. Mandal.

Output :
1

This algorithm takes O(m log m + n log n) time to sort and O(m + n) time to find the minimum
difference. Therefore, the overall runtime is O(m log m + n log n).

Find the two numbers with odd occurrences in an unsorted


array
Given an unsorted array that contains even number of occurrences for all numbers except two numbers.
Find the two numbers which have odd occurrences in O(n) time complexity and O(1) extra space.

Examples:

Input: {12, 23, 34, 12, 12, 23, 12, 45}


Output: 34 and 45

Input: {4, 4, 100, 5000, 4, 4, 4, 4, 100, 100}


Output: 100 and 5000

Input: {10, 20}


Output: 10 and 20

A naive method to solve this problem is to run two nested loops. The outer loop picks an element and
the inner loop counts the number of occurrences of the picked element. If the count of occurrences is
odd then print the number. The time complexity of this method is O(n^2).

We can use sorting to get the odd occurring numbers in O(nLogn) time. First sort the numbers using an
O(nLogn) sorting algorithm like Merge Sort, Heap Sort.. etc. Once the array is sorted, all we need to do
is a linear scan of the array and print the odd occurring number.

We can also use hashing. Create an empty hash table which will have elements and their counts. Pick
all elements of input array one by one. Look for the picked element in hash table. If the element is found
in hash table, increment its count in table. If the element is not found, then enter it in hash table with
count as 1. After all elements are entered in hash table, scan the hash table and print elements with odd
count. This approach may take O(n) time on average, but it requires O(n) extra space.

A O(n) time and O(1) extra space solution:


The idea is similar to method 2 of this post. Let the two odd occurring numbers be x and y. We use
bitwise XOR to get x and y. The first step is to do XOR of all elements present in array. XOR of all
elements gives us XOR of x and y because of the following properties of XOR operation.
1) XOR of any number n with itself gives us 0, i.e., n ^ n = 0
2) XOR of any number n with 0 gives us n, i.e., n ^ 0 = n
3) XOR is cumulative and associative.

So we have XOR of x and y after the first step. Let the value of XOR be xor2. Every set bit in xor2
indicates that the corresponding bits in x and y have values different from each other. For example, if x
= 6 (0110) and y is 15 (1111), then xor2 will be (1001), the two set bits in xor2 indicate that the
corresponding bits in x and y are different. In the second step, we pick a set bit of xor2 and divide array
elements in two groups. Both x and y will go to different groups. In the following code, the rightmost set
bit of xor2 is picked as it is easy to get rightmost set bit of a number. If we do XOR of all those elements
of array which have the corresponding bit set (or 1), then we get the first odd number. And if we do
XOR of all those elements which have the corresponding bit 0, then we get the other odd occurring
number. This step works because of the same properties of XOR. All the occurrences of a number will
go in same set. XOR of all occurrences of a number which occur even number number of times will
result in 0 in its set. And the xor of a set will be one of the odd occurring elements.

// Java program to find two odd


// occurring elements

import java.util.*;

class Main
{

/* Prints two numbers that occur odd


number of times. The function assumes
that the array size is at least 2 and
there are exactly two numbers occurring
odd number of times. */
static void printTwoOdd(int arr[], int size)
{
/* Will hold XOR of two odd occurring elements */
int xor2 = arr[0];

/* Will have only single set bit of xor2 */


int set_bit_no;
int i;
int n = size - 2;
int x = 0, y = 0;

/* Get the xor of all elements in arr[].


The xor will basically be xor of two
odd occurring elements */
for(i = 1; i < size; i++)
xor2 = xor2 ^ arr[i];

/* Get one set bit in the xor2. We get


rightmost set bit in the following
line as it is easy to get */
set_bit_no = xor2 & ~(xor2-1);

/* Now divide elements in two sets:


1) The elements having the
corresponding bit as 1.
2) The elements having the
corresponding bit as 0. */
for(i = 0; i < size; i++)
{
/* XOR of first set is finally going
to hold one odd occurring number x */
if((arr[i] & set_bit_no)>0)
x = x ^ arr[i];
/* XOR of second set is finally going
to hold the other odd occurring number y */
else
y = y ^ arr[i];
}

System.out.println("The two ODD elements are "+


x + " & " + y);
}

// main function
public static void main (String[] args)
{
int arr[] = {4, 2, 4, 5, 2, 3, 3, 1};
int arr_size = arr.length;
printTwoOdd(arr, arr_size);
}
}

Output:
The two ODD elements are 5 & 1

Time Complexity: O(n)


Auxiliary Space: O(1)

Find start and ending index of an element in an


unsorted array
Given an array of integers, task is to find the starting and ending position of a given key.
Examples:

Input : arr[] = {1, 2, 3, 4, 5, 5}


Key = 5
Output : Start index: 4
Last index: 5
Explanation: Starting index where 5
is present is 4 and ending address is 5.

Input :arr[] = {1, 3, 7, 8, 6},


Key = 2
Output : Key not present in array

Input :arr[] = {1, 8, 7, 8, 6},


Key = 7
Output : Only one occurrence of
key is present at index 2

We traverse array from beginning to find first occurrence. If element is present, then we traverse from
end also to find last occurrence.
// Java program to find starting and ending
// indexes of repeated numbers in an array

class Test {
// Function to find starting and end index
static void findIndex(int a[], int n, int key)
{
int start = -1;

// Traverse from beginning to find


// first occurrence
for (int i = 0; i < n; i++) {
if (a[i] == key) {
start = i;
break;
}
}

if (start == -1) {
System.out.println("Key not present in array");
return;
}

// Traverse from end to find last


// occurrence.
int end = start;
for (int i = n - 1; i >= start; i--) {
if (a[i] == key) {
end = i;
break;
}
}
if (start == end)
System.out.println("Only one key is present at index : " + start);
else {
System.out.println("Start index: " + start);
System.out.println("Last index: " + end);
}
}

// Driver method
public static void main(String args[])
{
int a[] = { 1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8 };

// Key to find
int key = 8;

// Calling method
findIndex(a, a.length, key);
}
}
Output:
Start index: 3
Last index: 10

Find the intersection of two unsorted arrays -


Interview Problem

Problem Description: Given two integer arrays A[] and B[] of size m and n, respectively. We need to
find the intersection of these two arrays. The intersection of two arrays is a list of distinct numbers
which are present in both the arrays. The numbers in the intersection can be in any order.

For example

Input: A[] = {1,4,3,2,5, 8,9} , B[] = {6,3,2,7,5}

Output: {3,2,5}

Input : A[] = {3,4,6,7,10, 12, 5}, B[] = {7,11,15, 18}

Output: {7}

Possible follow-up questions to ask the interviewer:-

1. Can you modify the arrays? (Ans: Yes)


2. What are the constraints on the length and elements of the array? (Ans: m>n, 1 <= m,n <= 10^5, -10^5
<= A[i], B[i] <= 10^5)
3. Can there be repeated elements in the array or between the arrays? (Ans: Yes, the possibility exists)

Designing efficient solutions

We are discussing four ways to solve this problem :

1. Brute force: Use nested loops


2. Sorting and binary search
3. Sorting and two-pointer approach
4. Using a Hash Table

1. Brute Force: Use nested loops


For each element in A[], perform a linear search on B[]. Keep on adding the common elements to a list.
To make sure the numbers in the list are unique, either check before adding new numbers to list or
remove duplicates from the list after adding all numbers.

Pseudo-Code
int[] findIntersection(int A[], int B[], int m, int n)
{
int ans[]
for ( i = 0 to m-1 )
{
for ( j = 0 to n-1 )
{
if ( A[i] == B[j] )
if ( A[i] not in ans)
ans.add(A[i])
}
}

return ans
}
Complexity Analysis

There are two loops in the solution where the outer loop runs n times and the inner loop runs m times.
So in the worst case, time complexity = O(m*n).

Space Complexity: worst-case = O(1) (Why? Some space is being consumed by answer list. Why isn't it
taken into consideration?)

Critical ideas to think!

• What would be the time and space complexity of removing duplicates from n size array?
• How can we improve the time complexity?

2. Sorting and binary search


In the brute force approach, we select elements from array A[] and linearly search for them in array B[].
We could increase the efficiency of searching the elements if we sort B[] and apply binary search to
search for the elements. Binary Search takes O(logn) time complexity.

Solution Steps

1. Declare answer list.


2. Sort B[] array in increasing order.
3. Search for each element in A[] in the sorted array B[]
4. If the element if found, add it to the answer list
5. Return answer list

Pseudo-Code
bool binary_search(int B[], int n, int K)
{
int low = 0, high = n

while( low <= high )


{
int mid = low + ( high - low ) / 2

if( B[mid] == K )
return True

else if( B[mid] > K )


high = mid - 1

else
low = mid + 1
}

return false
}

int[] findIntersection(int A[], int B[], int m, int n)


{
int ans[]
sort(B,n)

for(i = 0 to m-1)
{
if(binary_search(B, n, A[i]))
ans.add(A[i])
}

return ans
}
Complexity Analysis

Time Complexity: Sorting array B[] + Searching for all elements of A[] in B[] = O(nlogn) + O(mlogn) =
O(nlogn + mlogn)

Space Complexity: If we use merge sort, then space complexity is O(n), else if we use heap sort, space
complexity is O(1).

Critical ideas to think!

• Here, we sorted the smaller array. What if we sort the bigger array for the solution? How does the time
complexity changes?
• What would be the time and space complexity if we use quicksort? Compare different sorting algorithms
• What would be the space complexity if we use recursive binary search for the implementation?
• Prepare a list of problems where you can apply the idea of sorting and binary search.

Find the smallest positive number missing from an


unsorted array | Set 2
Given an unsorted array with both positive and negative elements. Find the smallest positive number
missing from the array in O(n) time using constant extra space. It is allowed to modify the original array.

Examples:
Input: {2, 3, 7, 6, 8, -1, -10, 15}
Output: 1

Input: { 2, 3, -7, 6, 8, 1, -10, 15 }


Output: 4

Input: {1, 1, 0, -1, -2}


Output: 2

We have discussed an O(n) time and O(1) extra space solution in previous post. In this post another
alternative solution is discussed.
We make the value at index corresponding to given array element equal to array element.

For example: consider the array = {2, 3, 7, 6, 8, -1, -10, 15}.

To mark presence of element 2 in this array, we make arr[2-1] = 2. In array subscript [2-1], 2 is element
to be marked and 1 is subtracted because we are mapping an element value range [1, N] on index value
range [0, N-1].

• But if we make arr[1] = 2, we will loss data stored at arr[1]. To avoid this, we first store value
present at arr[1] and then update it.
• Next we will mark presence of element previously present at arr[1], i.e. 3. Clearly this lead to
some type of random traversal over the array.

Now we have to specify a condition to mark the end of this traversal.

There are three conditions that mark the end of this traversal:\

1. If element to be marked is negative: No need to mark the presence of this element as we are
interested in finding the first missing positive integer. So if a negative element is found, simply
end the traversal as no more marking of presence of an element is done.
2. If element to be marked is greater than N : No need to mark the presence of this element because
if this element is present then certainly it has taken a place of an element in range [1, N] in array
of size N and hence ensuring that our answer lies in the range[1, N]. So simply end the traversal
as no more marking of presence of an element is done.
3. If presence of current element is already marked: Suppose element to be marked present is val. If
arr[val-1] = val, then we have already marked the presence of this element. So simply end the
traversal as no more marking of presence of an element is done.

Also note that it is possible that all the elements of array in the range [1, N] are not marked present in
current traversal. To ensure that all the elements in the range are marked present, we check each element
of the array lying in this range. If element is not marked, then we start a new traversal beginning from
that array element.
After we have marked presence of all array elements lying in the range [1, N], we check which index
value ind is not equal to ind+1. If arr[ind] is not equal to ind+1, then ind+1 is the smallest positive
missing number. Recall that we are mapping index value range [0, N-1] to element value range [1, N],
so 1 is added to ind. If no such ind is found, then all elements in the range [1, N] are present in the array.
So the first missing positive number is N+1.

How this solution works in O(n) time?


Observe that each element in range [1, N] is traversed at most twice in worst case. First while
performing a traversal started from some other element in the range. Second when checking if a new
traversal is required to be initiated from this element to mark the presence of unmarked elements. In
worst case each element in the range [1, N] are present in the array and thus all N elements are traversed
twice. So total computations are 2*n, and hence the time complexity is O(n).

/* Java program to find the smallest


positive missing number */
import java.io.*;

class GFG {

// Function to find smallest positive missing number.


static int findMissingNo(int []arr, int n)
{
// to store current array element
int val;

// to store next array element in current traversal


int nextval;

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

// if value is negative or greater


// than array size, then it cannot
// be marked in array. So move to
// next element.
if (arr[i] <= 0 || arr[i] > n)
continue;

val = arr[i];

// traverse the array until we


// reach at an element which
// is already marked or which
// could not be marked.
while (arr[val - 1] != val) {
nextval = arr[val - 1];
arr[val - 1] = val;
val = nextval;
if (val <= 0 || val > n)
break;
}
}

// find first array index which is


// not marked which is also the
// smallest positive missing
// number.
for (int i = 0; i < n; i++) {
if (arr[i] != i + 1) {
return i + 1;
}
}

// if all indices are marked, then


// smallest missing positive
// number is array_size + 1.
return n + 1;
}

// Driver code
public static void main (String[] args)
{
int arr[] = { 2, 3, 7, 6, 8, -1, -10, 15 };
int arr_size = arr.length;

int missing = findMissingNo(arr, arr_size);

System.out.println( "The smallest positive"


+ " missing number is " + missing);
}
}

// This code is contributed by anuj_67.


Output:
The smallest positive missing number is 1

Find the Minimum length Unsorted Subarray,


sorting which makes the complete array sorted
Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that
sorting this subarray makes the whole array sorted.

Examples:
1) If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find
that the subarray lies between the indexes 3 and 8.

2) If the input array is [0, 1, 15, 25, 6, 7, 30, 40, 50], your program should be able to find that the
subarray lies between the indexes 2 and 5.

Solution:
1) Find the candidate unsorted subarray
a) Scan from left to right and find the first element which is greater than the next element. Let s be the
index of such an element. In the above example 1, s is 3 (index of 30).
b) Scan from right to left and find the first element (first in right to left order) which is smaller than the
next element (next in right to left order). Let e be the index of such an element. In the above example 1,
e is 7 (index of 31).

2) Check whether sorting the candidate unsorted subarray makes the complete array sorted or
not. If not, then include more elements in the subarray.
a) Find the minimum and maximum values in arr[s..e]. Let minimum and maximum values be min and
max. min and max for [30, 25, 40, 32, 31] are 25 and 40 respectively.
b) Find the first element (if there is any) in arr[0..s-1] which is greater than min, change s to index of
this element. There is no such element in above example 1.
c) Find the last element (if there is any) in arr[e+1..n-1] which is smaller than max, change e to index of
this element. In the above example 1, e is changed to 8 (index of 35)

3) Print s and e.

// Java program to find the Minimum length Unsorted Subarray,


// sorting which makes the complete array sorted
class Main
{
static void printUnsorted(int arr[], int n)
{
int s = 0, e = n-1, i, max, min;

// step 1(a) of above algo


for (s = 0; s < n-1; s++)
{
if (arr[s] > arr[s+1])
break;
}
if (s == n-1)
{
System.out.println("The complete array is sorted");
return;
}

// step 1(b) of above algo


for(e = n - 1; e > 0; e--)
{
if(arr[e] < arr[e-1])
break;
}

// step 2(a) of above algo


max = arr[s]; min = arr[s];
for(i = s + 1; i <= e; i++)
{
if(arr[i] > max)
max = arr[i];
if(arr[i] < min)
min = arr[i];
}

// step 2(b) of above algo


for( i = 0; i < s; i++)
{
if(arr[i] > min)
{
s = i;
break;
}
}

// step 2(c) of above algo


for( i = n -1; i >= e+1; i--)
{
if(arr[i] < max)
{
e = i;
break;
}
}

// step 3 of above algo


System.out.println(" The unsorted subarray which"+
" makes the given array sorted lies"+
" between the indices "+s+" and "+e);
return;
}

public static void main(String args[])


{
int arr[] = {10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60};
int arr_size = arr.length;
printUnsorted(arr, arr_size);
}
}

Output :

The unsorted subarray which makes the given array


sorted lies between the indees 3 and 8

Time Complexity: O(n)


Find sub-arrays from given two arrays such
that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find
sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If
no such sub-arrays are possible then print -1.

Examples:

Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4}


Output:
Indices in array 1 : 0, 1, 2
Indices in array 2 : 0
A[0..2] = 1 + 2 + 3 = 6
B[0] = 6

Input: A[] = {10, 1}, B[] = {5, 3}


Output: -1
No such sub-arrays.

Approach: Let Ai denote the sum of first i elements in A and Bj denote the sum of first j elements in B.
Without loss of generality we assume that An <= Bn.
Now Bn >= An >= Ai. So for each Ai we can find the smallest j such that Ai <= Bj. For each i we find the
difference
B j – Ai .
If difference is 0 then we are done as the elements from 1 to i in A and 1 to j in B have the same sum.
Suppose difference is not 0.Then the difference must lie in the range [1, n-1].

Proof:
Let Bj – Ai >= n
Bj >= Ai + n
Bj-1 >= Ai (As the jth element in B can be at most n so Bj <= Bj-1 + n)
Now this is a contradiction as we had assumed that j is the smallest index
such that Bj >= Ai is j. So our assumption is wrong.
So Bj – Ai < n

Now there are n such differences(corresponding to each index) but only (n-1) possible values, so at least
two indices will produce the same difference(By Pigeonhole principle). Let Aj – By = Ai – Bx. On
rearranging we get Aj – Ai = By – Bx. So the required subarrays are [ i+1, j ] in A and [ x+1, y ] in B.

Below is the implementation of the above approach:


// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;

// Function to print the valid indices in the array


void printAns(int x, int y, int num)
{
cout << "Indices in array " << num << " : ";
for (int i = x; i < y; ++i) {
cout << i << ", ";
}
cout << y << "\n";
}

// Function to find sub-arrays from two


// different arrays with equal sum
void findSubarray(int N, int a[], int b[], bool swap)
{

// Map to store the indices in A and B


// which produce the given difference
std::map<int, pair<int, int> > index;
int difference;
index[0] = make_pair(-1, -1);
int j = 0;
for (int i = 0; i < N; ++i) {

// Find the smallest j such that b[j] >= a[i]


while (b[j] < a[i]) {
j++;
}
difference = b[j] - a[i];

// Difference encountered for the second time


if (index.find(difference) != index.end()) {

// b[j] - a[i] = b[idx.second] - a[idx.first]


// b[j] - b[idx.second] = a[i] = a[idx.first]
// So sub-arrays are a[idx.first+1...i] and b[idx.second+1...j]
if (swap) {
pair<int, int> idx = index[b[j] - a[i]];

printAns(idx.second + 1, j, 1);
printAns(idx.first + 1, i, 2);
}
else {
pair<int, int> idx = index[b[j] - a[i]];
printAns(idx.first + 1, i, 1);
printAns(idx.second + 1, j, 2);
}
return;
}

// Store the indices for difference in the map


index[difference] = make_pair(i, j);
}

cout << "-1";


}

// Utility function to calculate the


// cumulative sum of the array
void cumulativeSum(int arr[], int n)
{
for (int i = 1; i < n; ++i)
arr[i] += arr[i - 1];
}

// Driver code
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int b[] = { 6, 2, 1, 5, 4 };
int N = sizeof(a) / sizeof(a[0]);

// Function to update the arrays


// with their cumulative sum
cumulativeSum(a, N);
cumulativeSum(b, N);

if (b[N - 1] > a[N - 1]) {


findSubarray(N, a, b, false);
}
else {

// Swap is true as a and b are swapped during


// function call
findSubarray(N, b, a, true);
}

return 0;
}
Output:
Indices in array 1 : 0, 1, 2
Indices in array 2 : 0

Find the element that appears once in an array where


every other element appears twice
Given an array of integers. All numbers occur twice except one number which occurs once. Find the
number in O(n) time & constant extra space.

Example :

Input: ar[] = {7, 3, 5, 4, 5, 3, 4}


Output: 7

One solution is to check every element if it appears once or not. Once an element with a single
occurrence is found, return it. Time complexity of this solution is O(n2).

A better solution is to use hashing.


1) Traverse all elements and put them in a hash table. Element is used as key and the count of
occurrences is used as the value in the hash table.
2) Traverse the array again and print the element with count 1 in the hash table.
This solution works in O(n) time but requires extra space.

The best solution is to use XOR. XOR of all array elements gives us the number with a single
occurrence. The idea is based on the following two facts.
a) XOR of a number with itself is 0.
b) XOR of a number with 0 is number itself.

Let us consider the above example.


Let ^ be xor operator as in C and C++.

res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4

Since XOR is associative and commutative, above


expression can be written as:
res = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)
= 7 ^ 0 ^ 0 ^ 0
= 7 ^ 0
= 7

Below are implementations of above algorithm.

// Java program to find the array


// element that appears only once
class MaxSum
{
// Return the maximum Sum of difference
// between consecutive elements.
static int findSingle(int ar[], int ar_size)
{
// Do XOR of all elements and return
int res = ar[0];
for (int i = 1; i < ar_size; i++)
res = res ^ ar[i];

return res;
}

// Driver code
public static void main (String[] args)
{
int ar[] = {2, 3, 5, 4, 5, 3, 4};
int n = ar.length;
System.out.println("Element occurring once is " +
findSingle(ar, n) + " ");
}
}
// This code is contributed by Prakriti Gupta

Output:
Element occurring once is 2

The time complexity of this solution is O(n) and it requires O(1) extra space.

Find the two repeating elements in a given array


You are given an array of n+2 elements. All elements of the array are in range 1 to n. And all elements
occur once except two numbers which occur twice. Find the two repeating numbers.

For example, array = {4, 2, 4, 5, 2, 3, 1} and n = 5

The above array has n + 2 = 7 elements with all elements occurring once except 2 and 4 which occur
twice. So the output should be 4 2.

Method 1 (Basic)
Use two loops. In the outer loop, pick elements one by one and count the number of occurrences of the
picked element in the inner loop.

This method doesn’t use the other useful data provided in questions like range of numbers is between 1
to n and there are only two repeating elements.

class RepeatElement
{
void printRepeating(int arr[], int size)
{
int i, j;
System.out.println("Repeated Elements are :");
for (i = 0; i < size; i++)
{
for (j = i + 1; j < size; j++)
{
if (arr[i] == arr[j])
System.out.print(arr[i] + " ");
}
}
}

public static void main(String[] args)


{
RepeatElement repeat = new RepeatElement();
int arr[] = {4, 2, 4, 5, 2, 3, 1};
int arr_size = arr.length;
repeat.printRepeating(arr, arr_size);
}
}

Output :

Repeating elements are 4 2

Time Complexity: O(n*n)


Auxiliary Space: O(1)

Method 2 (Use Count array)


Traverse the array once. While traversing, keep track of count of all elements in the array using a temp
array count[] of size n, when you see an element whose count is already set, print it as duplicate.

This method uses the range given in the question to restrict the size of count[], but doesn’t use the data
that there are only two repeating elements.

class RepeatElement
{
void printRepeating(int arr[], int size)
{
int count[] = new int[size];
int i;

System.out.println("Repeated elements are : ");


for (i = 0; i < size; i++)
{
if (count[arr[i]] == 1)
System.out.print(arr[i] + " ");
else
count[arr[i]]++;
}
}

public static void main(String[] args)


{
RepeatElement repeat = new RepeatElement();
int arr[] = {4, 2, 4, 5, 2, 3, 1};
int arr_size = arr.length;
repeat.printRepeating(arr, arr_size);
}
}

Output :
Repeating elements are 4 2

Time Complexity: O(n)


Auxiliary Space: O(n)

K’th Smallest/Largest Element in Unsorted Array | Set 1


Given an array and a number k where k is smaller than size of array, we need to find the k’th smallest
element in the given array. It is given that ll array elements are distinct.

Examples:

Input: arr[] = {7, 10, 4, 3, 20, 15}


k=3
Output: 7

Input: arr[] = {7, 10, 4, 3, 20, 15}


k=4
Output: 10

Method 1 (Simple Solution)


A simple solution is to sort the given array using a O(N log N) sorting algorithm like Merge Sort, Heap
Sort, etc and return the element at index k-1 in the sorted array.

Time Complexity of this solution is O(N Log N)

// Java code for kth smallest element


// in an array
import java.util.Arrays;
import java.util.Collections;

class GFG {
// Function to return k'th smallest
// element in a given array
public static int kthSmallest(Integer[] arr,
int k)
{
// Sort the given array
Arrays.sort(arr);

// Return k'th element in


// the sorted array
return arr[k - 1];
}
// driver program
public static void main(String[] args)
{
Integer arr[] = new Integer[] { 12, 3, 5, 7, 19 };
int k = 2;
System.out.print("K'th smallest element is " + kthSmallest(arr, k));
}
}

// This code is contributed by Chhavi


Output:
K'th smallest element is 5

Rearrange array in alternating positive & negative items with


O(1) extra space | Set 2
Given an array of positive and negative numbers, arrange them in an alternate fashion such that every
positive number is followed by negative and vice-versa. Order of elements in output doesn’t matter.
Extra positive or negative elements should be moved to end.
Examples:

Input :
arr[] = {-2, 3, 4, -1}
Output :
arr[] = {-2, 3, -1, 4} OR {-1, 3, -2, 4} OR ..

Input :
arr[] = {-2, 3, 1}
Output :
arr[] = {-2, 3, 1} OR {-2, 1, 3}

Input :
arr[] = {-5, 3, 4, 5, -6, -2, 8, 9, -1, -4}
Output :
arr[] = {-5, 3, -2, 5, -6, 4, -4, 9, -1, 8}
OR ..

We strongly recommend you to minimize your browser and try this yourself first.
We have already discussed a O(n2) solution that maintains the order of appearance in the array here. If
we are allowed to change order of appearance, we can solve this problem in O(n) time and O(1) space.
The idea is to process the array and shift all negative values to the end in O(n) time. After all negative
values are shifted to the end, we can easily rearrange array in alternating positive & negative items. We
basically swap next positive element at even position from next negative element in this step.
Following is the implementation of above idea.

// Java program to rearrange


// array in alternating
// positive & negative
// items with O(1) extra space
class GFG {

// Function to rearrange positive and negative


// integers in alternate fashion. The below
// solution doesn't maintain original order of
// elements
static void rearrange(int arr[], int n)
{
int i = 0, j = n - 1;

// shift all negative values to the end


while (i < j)
{
//find fist negative number from right
while(i <= n - 1 && arr[i] > 0)
i += 1;
//find positive number from right
while (j >= 0 && arr[j] < 0)
j -= 1;
if (i < j)
swap(arr, i,j);
}

// i has index of leftmost negative element


if (i == 0 || i == n)
return;

// start with first positive


// element at index 0

// Rearrange array in alternating positive &


// negative items
int k = 0;
while (k < n && i < n)
{
// swap next positive element
// at even position
// from next negative element.
swap(arr,k,i);
i = i + 1;
k = k + 2;
}
}

// Utility function to print an array


static void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
static void swap(int arr[], int index1, int index2)
{
int c = arr[index1];
arr[index1]=arr[index2];
arr[index2]=c;
}

// Driver code
public static void main(String[] args)
{
int arr[] = {2, 3, -4, -1, 6, -9};

int n = arr.length;

System.out.println("Given array is ");


printArray(arr, n);

rearrange(arr, n);

System.out.println("Rearranged array is ");


printArray(arr, n);
}
}

// This code is contributed by 29AjayKumar

Output:

Given array is
2 3 -4 -1 6 -9
Rearranged array is
-1 3 -4 2 -9 6

Remove duplicates from sorted array


Given a sorted array, the task is to remove the duplicate elements from the array.

Examples:

Input : arr[] = {2, 2, 2, 2, 2}


Output : arr[] = {2}
new size = 1

Input : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}


Output : arr[] = {1, 2, 3, 4, 5}
new size = 5

Method 1: (Using extra space)

1. Create an auxiliary array temp[] to store unique elements.


2. Traverse input array and one by one copy unique elements of arr[] to temp[]. Also keep track of count of
unique elements. Let this count be j.
3. Copy j elements from temp[] to arr[] and return j

// simple java program to remove


// duplicates

class Main
{
// Function to remove duplicate elements
// This function returns new size of modified
// array.
static int removeDuplicates(int arr[], int n)
{
// Return, if array is empty
// or contains a single element
if (n==0 || n==1)
return n;

int[] temp = new int[n];

// Start traversing elements


int j = 0;
for (int i=0; i<n-1; i++)
// If current element is not equal
// to next element then store that
// current element
if (arr[i] != arr[i+1])
temp[j++] = arr[i];

// Store the last element as whether


// it is unique or repeated, it hasn't
// stored previously
temp[j++] = arr[n-1];

// Modify original array


for (int i=0; i<j; i++)
arr[i] = temp[i];

return j;
}

public static void main (String[] args)


{
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = arr.length;

n = removeDuplicates(arr, n);

// Print updated array


for (int i=0; i<n; i++)
System.out.print(arr[i]+" ");
}
}

Output:

1 2 3 4 5

Time Complexity : O(n)


Auxiliary Space : O(n)

Method 2: (Constant extra space)


Just maintain a separate index for same array as maintained for different array in Method 1.

// simple java program to remove


// duplicates

class Main
{
// Function to remove duplicate elements
// This function returns new size of modified
// array.
static int removeDuplicates(int arr[], int n)
{
if (n == 0 || n == 1)
return n;

// To store index of next unique element


int j = 0;

// Doing same as done in Method 1


// Just maintaining another updated index i.e. j
for (int i = 0; i < n-1; i++)
if (arr[i] != arr[i+1])
arr[j++] = arr[i];

arr[j++] = arr[n-1];

return j;
}

public static void main (String[] args)


{
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n = arr.length;

n = removeDuplicates(arr, n);

// Print updated array


for (int i=0; i<n; i++)
System.out.print(arr[i]+" ");
}
}
/* This code is contributed by Harsh Agarwal */

Output:
1 2 3 4 5

Time Complexity : O(n)


Auxiliary Space : O(1)

Remove Duplicates from Sorted Array (Java)


Given a sorted array, remove the duplicates in place such that each element appear only once and return
the new length. Do not allocate extra space for another array, you must do this in place with constant
memory.

For example, given input array A = [1,1,2], your function should return length = 2, and A is now [1,2].

Analysis

The problem is pretty straightforward. It returns the length of the array with unique elements, but the
original array need to be changed also.

Java Solution

public static int removeDuplicates(int[] A) {


if (A.length < 2)
return A.length;

int j = 0;
int i = 1;

while (i < A.length) {


if (A[i] != A[j]) {
j++;
A[j] = A[i];
}

i++;
}

return j + 1;
}

Note that we only care about the first unique part of the original array. So it is ok if input array is {1, 2,
2, 3, 3}, the array is changed to {1, 2, 3, 3, 3}.

Largest Sum Contiguous Subarray


Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of
numbers which has the largest sum.

Kadane’s Algorithm:

Initialize:
max_so_far = 0
max_ending_here = 0

Loop for each element of the array


(a) max_ending_here = max_ending_here + a[i]
(b) if(max_so_far < max_ending_here)
max_so_far = max_ending_here
(c) if(max_ending_here < 0)
max_ending_here = 0
return max_so_far

Explanation:
Simple idea of the Kadane’s algorithm is to look for all positive contiguous segments of the array
(max_ending_here is used for this). And keep track of maximum sum contiguous segment among all
positive segments (max_so_far is used for this). Each time we get a positive sum compare it with
max_so_far and update max_so_far if it is greater than max_so_far

Lets take the example:


{-2, -3, 4, -1, -2, 1, 5, -3}

max_so_far = max_ending_here = 0

for i=0, a[0] = -2


max_ending_here = max_ending_here + (-2)
Set max_ending_here = 0 because max_ending_here < 0

for i=1, a[1] = -3


max_ending_here = max_ending_here + (-3)
Set max_ending_here = 0 because max_ending_here < 0

for i=2, a[2] = 4


max_ending_here = max_ending_here + (4)
max_ending_here = 4
max_so_far is updated to 4 because max_ending_here greater
than max_so_far which was 0 till now

for i=3, a[3] = -1


max_ending_here = max_ending_here + (-1)
max_ending_here = 3

for i=4, a[4] = -2


max_ending_here = max_ending_here + (-2)
max_ending_here = 1

for i=5, a[5] = 1


max_ending_here = max_ending_here + (1)
max_ending_here = 2

for i=6, a[6] = 5


max_ending_here = max_ending_here + (5)
max_ending_here = 7
max_so_far is updated to 7 because max_ending_here is
greater than max_so_far

for i=7, a[7] = -3


max_ending_here = max_ending_here + (-3)
max_ending_here = 4

Program:

import java.io.*;
// Java program to print largest contiguous array sum
import java.util.*;

class Kadane
{
public static void main (String[] args)
{
int [] a = {-2, -3, 4, -1, -2, 1, 5, -3};
System.out.println("Maximum contiguous sum is " +
maxSubArraySum(a));
}

static int maxSubArraySum(int a[])


{
int size = a.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
}

Output:
Maximum contiguous sum is 7

Above program can be optimized further, if we compare max_so_far with max_ending_here only if
max_ending_here is greater than 0.

static int maxSubArraySum(int a[],int size)


{

int max_so_far = 0, max_ending_here = 0;

for (int i = 0; i < size; i++)


{
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;

/* Do not compare for all


elements. Compare only
when max_ending_here > 0 */
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;

}
return max_so_far;
}

// This code is contributed by ANKITRAI1

Time Complexity: O(n)


Algorithmic Paradigm: Dynamic Programming

Following is another simple implementation suggested by Mohit Kumar. The implementation handles
the case when all numbers in array are negative.

// Java program to print largest contiguous


// array sum
import java.io.*;
class GFG {

static int maxSubArraySum(int a[], int size)


{
int max_so_far = a[0];
int curr_max = a[0];

for (int i = 1; i < size; i++)


{
curr_max = Math.max(a[i], curr_max+a[i]);
max_so_far = Math.max(max_so_far, curr_max);
}
return max_so_far;
}

/* Driver program to test maxSubArraySum */


public static void main(String[] args)
{
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int n = a.length;
int max_sum = maxSubArraySum(a, n);
System.out.println("Maximum contiguous sum is "
+ max_sum);
}
}

// This code is contributd by Prerna Saini

Output:
Maximum contiguous sum is 7

To print the subarray with the maximum sum, we maintain indices whenever we get the maximum sum.

// Java program to print largest


// contiguous array sum
class GFG {

static void maxSubArraySum(int a[], int size)


{
int max_so_far = Integer.MIN_VALUE,
max_ending_here = 0,start = 0,
end = 0, s = 0;

for (int i = 0; i < size; i++)


{
max_ending_here += a[i];

if (max_so_far < max_ending_here)


{
max_so_far = max_ending_here;
start = s;
end = i;
}
if (max_ending_here < 0)
{
max_ending_here = 0;
s = i + 1;
}
}
System.out.println("Maximum contiguous sum is "
+ max_so_far);
System.out.println("Starting index " + start);
System.out.println("Ending index " + end);
}

// Driver code
public static void main(String[] args)
{
int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n = a.length;
maxSubArraySum(a, n);
}
}

// This code is contributed by prerna saini

Output:
Maximum contiguous sum is 7
Starting index 2
Ending index 6

Now try below question


Given an array of integers (possibly some of the elements negative), write a C program to find out the
*maximum product* possible by multiplying ‘n’ consecutive integers in the array where n <=
ARRAY_SIZE. Also print the starting point of maximum product subarray.

Maximum Product Subarray


Given an array that contains both positive and negative integers, find the product of the maximum
product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used.

Examples:

Input: arr[] = {6, -3, -10, 0, 2}


Output: 180 // The subarray is {6, -3, -10}

Input: arr[] = {-1, -3, -10, 0, 60}


Output: 60 // The subarray is {60}

Input: arr[] = {-2, -40, 0, -2, -3}


Output: 80 // The subarray is {-2, -40}

Naive Solution:
The idea is to traverse over every contiguous subarrays, find the product of each of these subarrays and
return the maximum product from these results.

Below is the implementation of the above approach.

// Java program to find maximum product subarray


import java.io.*;

class GFG {
/* Returns the product of max product subarray.*/
static int maxSubarrayProduct(int arr[])
{
// Initializing result
int result = arr[0];
int n = arr.length;

for (int i = 0; i < n; i++)


{
int mul = arr[i];
// traversing in current subarray
for (int j = i + 1; j < n; j++)
{
// updating result every time
// to keep an eye over the
// maximum product
result = Math.max(result, mul);
mul *= arr[j];
}
// updating the result for (n-1)th index.
result = Math.max(result, mul);
}
return result;
}

// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, -2, -3, 0, 7, -8, -2 };
System.out.println("Maximum Sub array product is "
+ maxSubarrayProduct(arr));
}
}

// This code is contributed by yashbeersingh42

Output:

Maximum Sub array product is 112

Time Complexity: O(N2)


Auxiliary Space: O(1)
Efficient Solution:

The following solution assumes that the given input array always has a positive output. The solution
works for all cases mentioned above. It doesn’t work for arrays like {0, 0, -20, 0}, {0, 0, 0}.. etc. The
solution can be easily modified to handle this case.
It is similar to Largest Sum Contiguous Subarray problem. The only thing to note here is, maximum
product can also be obtained by minimum (negative) product ending with the previous element
multiplied by this element. For example, in array {12, 2, -3, -5, -6, -2}, when we are at element -2, the
maximum product is multiplication of, minimum product ending with -6 and -2.

// Java program to find maximum product subarray


import java.io.*;

class ProductSubarray {

// Utility functions to get


// minimum of two integers
static int min(int x, int y) {
return x < y ? x : y;
}

// Utility functions to get


// maximum of two integers
static int max(int x, int y) {
return x > y ? x : y;
}

/* Returns the product of


max product subarray.
Assumes that the given
array always has a subarray
with product more than 1 */
static int maxSubarrayProduct(int arr[])
{
int n = arr.length;
// max positive product
// ending at the current
// position
int max_ending_here = 1;

// min negative product


// ending at the current
// position
int min_ending_here = 1;

// Initialize overall max product


int max_so_far = 0;
int flag = 0;

/* Traverse through the array. Following


values are maintained after the ith iteration:
max_ending_here is always 1 or some positive product
ending with arr[i]
min_ending_here is always 1 or some negative product
ending with arr[i] */
for (int i = 0; i < n; i++)
{
/* If this element is positive, update
max_ending_here. Update min_ending_here only
if min_ending_here is negative */
if (arr[i] > 0)
{
max_ending_here = max_ending_here * arr[i];
min_ending_here
= min(min_ending_here * arr[i], 1);
flag = 1;
}

/* If this element is 0, then the maximum


product cannot end here, make both
max_ending_here and min_ending _here 0
Assumption: Output is alway greater than or
equal to 1. */
else if (arr[i] == 0)
{
max_ending_here = 1;
min_ending_here = 1;
}

/* If element is negative. This is tricky


max_ending_here can either be 1 or positive.
min_ending_here can either be 1 or negative.
next min_ending_here will always be prev.
max_ending_here * arr[i]
next max_ending_here will be 1 if prev
min_ending_here is 1, otherwise
next max_ending_here will be
prev min_ending_here * arr[i] */
else {
int temp = max_ending_here;
max_ending_here
= max(min_ending_here * arr[i], 1);
min_ending_here = temp * arr[i];
}

// update max_so_far, if needed


if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}

if (flag == 0 && max_so_far == 0)


return 0;
return max_so_far;
}

// Driver Code
public static void main(String[] args)
{

int arr[] = { 1, -2, -3, 0, 7, -8, -2 };


System.out.println("Maximum Sub array product is "
+ maxSubarrayProduct(arr));
}
} /*This code is contributed by Devesh Agrawal*/
Output
Maximum Sub array product is 112

Time Complexity: O(n)


Auxiliary Space: O(1)

How to Find All Permutations of String in Java using


Recursion
There are two main ways to solve this problem, using loops or by using recursion, the second one is what the
interviewer expects. Since recursion is a tricky programming concept to master, it's not easy for every
programmer to solve this problem on the fly, especially if you are not coding on a daily basis or don't have that
highly sought after code sense.

Solution 1 - Final All Permutations of given String Using


Recursion and Loop
Now let's get back to the problem, Permutation refers to ordering of characters but it takes position into account
i.e. if you have String "ab" then it will have just 2 permutations "ab" and "ba", because position of character
in both String are different.

Similarly for a String of n characters there are !n (factorial of n) permutations are possible e.g. for a String of 3
characters like "xyz" has 6 possible permutations, xyz, xzy, yxz, yzx, zxy, zyx as seen in our example. As I told
there are two ways to solve this problem either by using for loop (iterative algorithm) or by using recursion, but
most elegant solution is combination of both loop and recursion.

If you remember the factorial problem you know that factorial is naturally recursive i.e. factorial of n is nothing
but n * factorial of n -1. Similarly, permutations are also a recursive problem e.g. permutation of n characters is
nothing but fixing one character and calculating permutation of n - 1 characters e.g. in the case of "xyz", you
can fix "x" and calculate permutation of "yz".

In order to calculate all permutation of a String, you need to repeat this exercise for all characters one at a time.
This is where for loop comes into the picture. So, this solution uses both for loop and recursion to print all
permutation of given String.

In the case of recursion, the most important question is the base case, because that is responsible for stopping
recursive call. If you don't have a base case then your program will eventually terminate with
java.lang.StackOverFlowError.
In this problem, our base case is a permutation of empty String, which is nothing but the empty String itself. After
each call, problem set is reduced and inches towards the base case, when it reaches there stack starts rolling down
and calculates the result.

Java Program to Print All Permutation of a String

Here is our sample Java program to print all permutations of given String using recursive algorithm. It uses both
loop and recursive call to solve this problem. It also demonstrate a technique of hiding your implementation detail
using a private method and exposing a much cleaner public method as API. In our solution, we have two
permutation method, one is public and other is private.

First method is clean and exposed to client but second method require you to pass an empty String as initial value
of perm parameter which is used to store intermediate permutation of String.

If you expose this method to client then it will wonder about this empty String, since it's part of implementation,
its better to hide and get rid of it as soon as you have a better algorithm to solve this problem, how about taking it
as an exercise?

/**
* Java program to find all permutations of a given String using recursion.
* For example, given a String "XYZ", this program will print all 6 possible
permutations of
* input e.g. XYZ, XZY, YXZ, YZX, ZXY, XYX
*
* @author Javin Paul
*/
public class StringPermutations {

public static void main(String args[]) {


permutation("123");
}

/*
* A method exposed to client to calculate permutation of String in Java.
*/
public static void permutation(String input){
permutation("", input);
}
/*
* Recursive method which actually prints all permutations
* of given String, but since we are passing an empty String
* as current permutation to start with,
* I have made this method private and didn't exposed it to client.
*/
private static void permutation(String perm, String word) {
if (word.isEmpty()) {
System.err.println(perm + word);

} else {
for (int i = 0; i <; word.length(); i++) {
permutation(perm + word.charAt(i), word.substring(0, i)
+ word.substring(i + 1, word.length()));
}
}

}
}
Output:
123
132
213
231
312
321

Like everything else, practice is your friend, doing this kind of coding exercises on a daily basis, solving
programming puzzles and doing more complex programs available on internet sites like project Euler, TopCoder
will help you to build confidence in your coding and problem-solving skill.

Explanation of Code :
All code for calculating permutation of String is inside permutation(String perm, String
word) method, I have purposefully made this method private because of additional parameter I am passing as an
initial value of permutation.

This demonstrates a technique of hiding implementation detail from a client and exposing much cleaner API to
client e.g. just permutation(String input) method, passing empty String is an implementation detail
and ugly for a client to pass whenever it needs to calculate permutation. It is also an exercise for you to see if you
can improve the code by getting rid of that empty String.

Algorithm is nothing but keeping one character fix and then calculating permutations of others. Crux of program
is in following code segment :

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


permutation(perm + word.charAt(i), word.substring(0, i)
+ word.substring(i + 1, word.length()));
}

Here we have a for loop to go through each character of String e.g. for input "123" this loop will run three times.
In each iteration, we are making a recursive call to function itself i.e. permutation(String perm,
String word) method, where the first parameter is used to store the result.

After 1st iteration perm (first parameter of permutation() method) will be "" + 1 as we are doing
word.charAt(i) and i is zero. Next, we take out that character and pass the remaining characters to
permutation method again e.g. "23" in the first iteration. Recursive call ends when it reaches to base case i.e.
when remaining word becomes empty, at that point "perm" parameter contains a valid permutation to be printed.
You can also store it into a List if you want to.

Here is a nice diagram which visually shows what this algorithm does :

That's all on how to find all permutations of a String in Java using recursion. It's a very good exercise for
preparing Java coding interviews. Why not you give it a try and come up with another solution? also could you
calculate complexity of this algorithm, to me it looks n*!n because loop will run for n times and for each n, we
will call permutation method. Also, how about writing some JUnit test cases to see if this solution works for
various input e.g. empty String, one letter String, many letters String, String with duplicate characters etc? It's a
good practice to become hands-on writing JUnit tests.
String Rotation in Java - How to check if strings are
rotations of each other or not
String-based algorithmic questions are very popular in Java interviews e.g. checking if two String is the anagram
of each other (see), or checking if given String is a palindrome (see), or just finding permutations of given String
(see). One of such popular String-based interview questions is about to check if two Strings are a rotation of each
other in Java. In order to solve this question, you should know what is String rotation? Well, A string is made of
characters and you just rotate the String around any character like "programming" will become
"ingprogramm" if we rotate the String on trailing character 3 times.

A k-rotation on a string takes the trailing k characters of the string and attaches it to the beginning of the string in
the same order.
You can rotate the String either in the clockwise (right from the top) or anti-clockwise(left from the top). The
string can also be rotated in one go like "123456" will become "456123" if we rotate 456 to the left around
character "3".

Problem:
Write a program to check if two given String s1 and s2 are rotations of another. For example

✓ if s1 = "IndiaUSAEngland" and s2= "USAEnglandIndia" then your program should return


true but

✓ if s2="IndiaEnglandUSA" then it should return false.

For the purpose of this program, you can assume that Strings are rotated on the right side, but you should
ask this question to your interviewer before jumping into the solution. Paying attention to such details
score brownie points on real Interview.

How to check if strings are rotations of each other or not


The simplest solution to this complex problem is to concatenate the String with itself and check if the given
rotation exists in this concatenated String. If it exists then the second string is a rotation of the first string.

before concatenating String, you should also first check the length of the two String. If they are of a different
length than two strings are definitely not the rotation of each other, but if they have the same length then you need
to check further.

This will result in faster solutions because checking length is faster than checking if a substring exists in the given
String.

Here is the exact algorithm to check if a given String is a rotation of another:

1) check the length of two strings, if the length is not same then return false
2) concatenate given string to itself
3) check if the rotated version of String exists in this concatenated string
4) if yes, then the second String is rotated version of the first string

This kind of little tricks really helps to solve coding problems during programming job interviews and in your
day-to-day life.

This will also help you to improve your coding sense by developing pattern recognition and art of developing a
bigger unknown problem into smaller known ones.

Anyway, here is the logic to check if two strings are rotation of each other in code:
Java Program to check if One String Rotation of Another
And, here is our complete Java program to check if a given string is the rotation of another given String or not.
import java.util.Scanner;
/*
* Java Program to check if one String is rotation of
* another.
*/
public class Main {
public static void main(String[] args) throws Exception {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter original String");
String input = scnr.nextLine();
System.out.println("Please enter rotation of String");
String rotation = scnr.nextLine();

if (checkRotatation(input, rotation)) {
System.out.println(input + " and " + rotation
+ " are rotation of each other");
} else {
System.out.println("Sorry, they are not rotation of another");
}
scnr.close();
}
/**
* This method check is given strings are rotation of each other
* @param original
* @param rotation
* @return true or false
*/
public static boolean checkRotatation(String original, String rotation) {
if (original.length() != rotation.length()) {
return false;
}
String concatenated = original + original;
if (concatenated.indexOf(rotation) != -1) {
return true;
}
return false;
}
}
Output
Please enter original String
IndiaVsAustralia
Please enter rotation of String
AustraliaVsIndia
Sorry, they are not the rotation of another

Please enter original String


IndiaVsEngland
Please enter rotation of String
EnglandIndiaVs
IndiaVsEngland and EnglandIndiaVs are rotation of each other

How to count Vowels and Consonants in Java String Word


In this article, we will take on a popular programming exercise of counting vowels in a word. You need to write a
Java program to count how many vowels in a String, which is entered from the command prompt. It's similar
to the program of counting the occurrence of characters in a String, in fact, it's a special case, where you need to
count occurrences of all vowels, which includes five characters a, e, i, o and u. We will further use Scanner
to get input from the user, as shown in this article. Though I have put down all code inside the main method for
quick testing, if you are asked to write this program as part of your homework or during the interview, better
writing a method called public int countVowels(String word) and put the logic of counting vowels
there. That's a better coding style than writing everything inside the main method.
By the way, you can also use this logic to count number of consonants in a Java String. What you need to do is
first count number of vowels and then subtract those characters from length of String, but remember this will only
work if your String contains only alphabetic words, if it contains special character like @, _, | or numbers like
1,2,3 etc, than it will not work.

In that case you need to extend your logic to only count consonants, by extending your switch case to include rest
of 21 characters from English alphabets.

Java Program to count vowels and consonants in String


import java.util.Scanner;

/**
* Java Program to count vowels in a String. It accept a String from command
prompt
* and count how many vowels it contains. To revise, 5 letters a, e, i, o and u
are known as vowels in English.
*/
public class VowelCounter {

public static void main(String args[]) {


System.out.println("Please enter some text");
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
char[] letters = input.toCharArray();

int count = 0;
for (char c : letters) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
default:
// no count increment
}
}
System.out.println("Number of vowels in String [" + input + "] is : " +
count);
}
}

Output:
Please enter some text
How many vowels in this String
Number of vowels in String [How many vowels in this String] is: 7

Madhav array
1. A Madhav array has the following property.
a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a [9] = ...
The length of a Madhav array must be n*(n+1)/2 for some n.

Write a method named isMadhavArray that returns 1 if its array argument is a Madhav
array, otherwise it returns 0. If you are programming in Java or C# the function signature is
int isMadhavArray(int[ ] a)

If you are programming in C or C++, the function signature is


int isMadhavArray(int a[ ], int len) where len is the number of elements in a.
Examples
if a is return reason

{2, 1, 1} 1 2 + 1 +1
{2, 1, 1, 4, -1, -1} 1 2 = 1+ 1, 2 = 4 + -1 + -1
{6, 2, 4, 2, 2, 2, 1, 5, 0, 0} 1 6 = 2 + 4, 6 = 2 + 2 + 2, 6 = 1 + 5 + 0 +
0
{18, 9, 10, 6, 6, 6} 0 18 != 9 + 10
{-6, -3, -3, 8, -5, -4} 0 -6 != 8 + -5 + -4
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 0 = 0 + 0, 0 = 0 + 0 + 0, 0 = 0 + 0 + 0
1, -2, -1} +0,
0=1+1+1+ -2 + -1
{3, 1, 2, 3, 0} 0 The length of the array is 5, but 5 does not
equal n*(n+1)/2 for any value of n.

public class isMadhavArray{


public static void main(String[] args){
int result = isMadhavArray(new int[]{2, 1, 1});
System.out.println(result);
result = isMadhavArray(new int[]{2, 1, 1, 4, -1, -1});
System.out.println(result);
result = isMadhavArray(new int[]{6, 2, 4, 2, 2, 2, 1, 5, 0, 0});
System.out.println(result);
result = isMadhavArray(new int[]{18, 9, 10, 6, 6, 6});
System.out.println(result);
result = isMadhavArray(new int[]{-6, -3, -3, 8, -5, -4});
System.out.println(result);
result = isMadhavArray(new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 1, -2, -1});
System.out.println(result);
result = isMadhavArray(new int[]{3, 1, 2, 3, 0});
System.out.println(result);
}

static int isMadhavArray(int[] a){


int isMadhavArray = 0;
int arrayLength = a.length;
int startIndex = 0; // start index of current array elements
under consideration
int endIndex = 0; // end index of current array elements under
consideration
int n = 1; // track current length of array elements between
start and end index
int currentSum = 0; // current sum of array elements
int sum = 0; // sum of elements of array between startIndex and
endIndex
int currentLengthOfArray = 1; // length of array from index 0 to
endIndex
int calculatedLengthOfArray = 1; // length calculating n *
(n+1)/2
while(currentLengthOfArray <= arrayLength){
if(currentLengthOfArray == calculatedLengthOfArray){
for(int index = startIndex; index <= endIndex;
index++){
sum += a[index];
}
}else{
// Fail ::: The length of a Madhav array must be
n*(n+1)/2 for some n
isMadhavArray = 0;
break;
}
if((currentSum == sum) || (startIndex == endIndex)){ //
startIndex == endIndex to satisfy initial condition
currentSum = sum;
sum = 0;
isMadhavArray = 1;
}else{
// Fail ::: The sum is not equal
isMadhavArray = 0;
break;
}
if(currentLengthOfArray == arrayLength){
// already at the end of the array
break;
}else{
startIndex = endIndex + 1;
endIndex = startIndex + n;
if((startIndex < arrayLength && endIndex <
arrayLength)){
// operating inside the array bounderies
n++;
}else{
// adjusting boundries; so that lastIndex points
last element of array
endIndex = arrayLength - 1;
n = endIndex - startIndex;
}
calculatedLengthOfArray = n * (n + 1)/2;
currentLengthOfArray = endIndex + 1;
}
}
return isMadhavArray;
}
}
2. An array is defined to be inertial if the following
conditions hold:
a. it contains at least one odd value
b. the maximum value in the array is even
c. every odd value is greater than every even value that is not the maximum value.

So {11, 4, 20, 9, 2, 8} is inertial because


a. it contains at least one odd value
b. the maximum value in the array is 20 which is even
c. the two odd values (11 and 9) are greater than all the
even values that are not equal to 20 (the maximum), i.e., (4, 2, 8}.

However, {12, 11, 4, 9, 2, 3, 10} is not inertial because it fails condition (c), i.e.,
10 (which is even) is greater 9 (which is odd) but 10 is not the maximum value in
the array.

Write a function called isIntertial that accepts an integer array and


returns 1 if the array is inertial; otherwise it returns 0.

If you are programming in Java or C#, the


function signature is int isInertial(int[ ]
a)

If you are programming in C or C++, the function signature is


int isInertial(int a[ ], int len) where len is the number of

elements in the array Some other examples:


if the input array is return reason
{1} 0 fails condition (a) - the maximum value must be
even
{2} 0 fails condition (b) - the array must contain at
least one odd value.
fails condition (c) - 1 (which is odd) is not greater
than all even values other than the maximum (1 is
{1, 2, 3, 4} 0 less than 2 which is not the maximum)

there is no even number other than the maximum.


{1, 1, 1, 1, 1, 1, 2} 1 Hence, there can be no other even
values that are greater than 1.
11, the only odd value is greater than all even
{2, 12, 4, 6, 8, 11} 1 values except 12 which is the maximum value
in the array.
{2, 12, 12, 4, 6, 8, 11} 1 same as previous, i.e., it is OK if maximum
value occurs more than once.
{-2, -4, -6, -8, -11} 0 -8, which is even, is not the maximum value but
is greater than -11 which is odd
{2, 3, 5, 7} 0 the maximum value is odd
{2, 4, 6, 8, 10} 0 there is no odd value in the array.
public class isInertial{
public static void main(String[] args){
int result = isInertial(new int[]{1});
System.out.println(result);
result = isInertial(new int[]{2});
System.out.println(result);
result = isInertial(new int[]{1, 2, 3, 4});
System.out.println(result);
result = isInertial(new int[]{1, 1, 1, 1, 1, 1, 2});
System.out.println(result);
result = isInertial(new int[]{2, 12, 4, 6, 8, 11});
System.out.println(result);
result = isInertial(new int[]{2, 12, 12, 4, 6, 8, 11});
System.out.println(result);
result = isInertial(new int[]{-2, -4, -6, -8, -11});
System.out.println(result);
result = isInertial(new int[]{2, 3, 5, 7});
System.out.println(result);
result = isInertial(new int[]{2, 4, 6, 8, 10});
System.out.println(result);
}

static int isInertial(int[] a){


int isInertial = 0;
boolean containsOddValue = false;
int maxValue = Integer.MIN_VALUE;

int[] oddValues = new int[a.length];


int[] evenValues = new int[a.length];

int oddValuesIndex = 0;
int evenValuesIndex = 0;
for(int index = 0; index < a.length; index++){
if((a[index] % 2) != 0){
containsOddValue = true;
oddValues[oddValuesIndex] = a[index];
oddValuesIndex++;
}else{
evenValues[evenValuesIndex] = a[index];
evenValuesIndex++;
}
if(a[index] > maxValue){
maxValue = a[index];
}
}

if(containsOddValue){
if(maxValue % 2 == 0){
for(int oddIndex = 0; oddIndex < oddValuesIndex;
oddIndex++){
for(int evenIndex = 0; evenIndex <
evenValuesIndex; evenIndex++){
if(evenValues[evenIndex] != maxValue){
if(oddValues[oddIndex] >
evenValues[evenIndex]){
isInertial = 1;
}else{
isInertial = 0;
break;
}
}else{
isInertial = 1;
}
}
if(isInertial == 0){
break;
}
}
}
}
return isInertial;
}
}

There are three questions on this exam. You have two hours to
complete it. Please do your own work.
1. Define a square pair to be the tuple <x, y> where x and y are positive, non-zero integers, x<y
and x + y is a perfect square. A perfect square is an integer whose square root is also an integer,
e.g. 4, 9, 16 are perfect squares but 3, 10 and 17 are not. Write a function named
countSquarePairs that takes an array and returns the number of square pairs that can be
constructed from the elements in the array. For example, if the array is {11, 5, 4, 20} the
function would return 3 because the only square pairs that can be constructed from those
numbers are <5, 11>, <5, 20> and <4, 5>. You may assume that there exists a function named
isPerfectSquare that returns 1 if its argument is a perfect square and 0 otherwise. E.G.,
isPerfectSquare(4) returns 1 and isPerfectSquare(8) returns 0.
If you are programming in Java or C#, the function signature is int countSquarePairs(int[ ] a)

If you are programming in C++ or C, the function signature is int countSquarePairs(int a[ ], int len)
where len is the number of elements in the array.

You may assume that there are no duplicate values in the array, i.e, you don't have to deal with an
array like {2, 7, 2, 2}.

Examples:
if a is return reason
{9, 0, 2, -5, 7} 2 The square pairs are <2, 7> and <7, 9>. Note that <-5, 9> and
<0, 9> are not square pairs, even though they sum to perfect
squares, because both members of a square pair have to be
greater than 0.
Also <7,2> and <9,7> are not square pairs because the first
number has to be less than the second number.
{9} 0 The array must have at least 2 elements

public class countSquarePairs{


public static void main(String[] args){
int result = countSquarePairs(new int[]{11, 5, 4, 20});
System.out.println(result);
result = countSquarePairs(new int[]{9, 0, 2, -5, 7});
System.out.println(result);
result = countSquarePairs(new int[]{9});
System.out.println(result);
}

static int countSquarePairs(int[] a){


int countSquarePairs = 0;
for(int targetIndex = 0; targetIndex < a.length; targetIndex++){
for(int compareIndex = 0; compareIndex < a.length; compareIndex++){
if(a[targetIndex] > 0 && a[compareIndex] > 0){
if(a[targetIndex] < a[compareIndex]){
if(isPerfectSquare(a[targetIndex] + a[compareIndex]) == 1){
countSquarePairs ++;
}
}
}
}
}
return countSquarePairs;
}

static int isPerfectSquare(int element){


int isPerfectSquare = 0;
if(element >= 0){
double sqrtResult = Math.sqrt(element);
int base = (int) sqrtResult;
if((sqrtResult - base) == 0){
isPerfectSquare = 1;
}else{
isPerfectSquare = 0;
}
}
return isPerfectSquare;
}
}

1. A prime number is an integer that is divisible only by 1 and itself. A porcupine number
is a prime number whose last digit is 9 and the next prime number that follows it also ends
with the digit 9. For example 139 is a porcupine number because:
a. it is prime
b. it ends in a 9
c. The next prime number after it is 149 which also ends in 9. Note that 140, 141, 142, 143, 144,
145, 146, 147 and 148 are not rime so 149 is the next prime number after 139.

Write a method named findPorcupineNumber which takes an integer argument n and returns
the first porcupine number that is greater than n. So findPorcupineNumber(0) would return
139 (because 139 happens to be the first porcupine number) and so would
findPorcupineNumber(138). But findPorcupineNumber(139) would return 409 which is
the second porcupine number.

The function signature is int findPorcupineNumber(int n)

You may assume that a porcupine number greater than n exists.

You may assume that a function isPrime exists that returns 1 if its argument is prime,
otherwise it returns 0. E.G., isPrime(7) returns 1 and isPrime(8) returns 0.
Hint: Use modulo base 10 arithmetic to get last digit of a number.

public class findPorcupineNumber{


public static void main(String[] args){
int result = findPorcupineNumber(0);
System.out.println(result);
result = findPorcupineNumber(138);
System.out.println(result);
result = findPorcupineNumber(139);
System.out.println(result);
}

static int findPorcupineNumber(int n){


int porcupineNumber = 0;
int maxValue = Integer.MAX_VALUE;
boolean isPorcupineNumber = false;
n++;
while(n <= maxValue){
if(isPorcupineNumber){
if(isPrime(n) == 1){
if(n % 10 == 9){
break;
}
else{
isPorcupineNumber = false;
}
}
}
else{
if(isPrime(n) == 1){
if(n % 10 == 9){
isPorcupineNumber = true;
porcupineNumber = n;
}
}
}
n++;
}
return porcupineNumber;
}

static int isPrime(int number){


int isPrime = 0;
if(number > 1){
isPrime = 1;
for(int divider = 2; 2*divider <= number; divider++){
if(number % divider == 0){
isPrime = 0;
break;
}
}
}
return isPrime;
}
}
2. Consider the following algorithm Start with a positive number n if n is even
then divide by 2 if n is odd then multiply by 3 and add 1 continue this until n
becomes 1
The Guthrie sequence of a positive number n is defined to be the numbers generated
by the above algorithm. For example, the Guthrie sequence of the number 7 is
7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
It is easy to see that this sequence was generated from the number 7 by the above algorithm.
Since 7 is odd multiply by 3 and add 1 to get 22 which is the second number of the sequence.
Since 22 is even, divide by 2 to get 11 which is the third number of the sequence. 11 is odd so
multiply by 3 and add 1 to get 34 which is the fourth number of the sequence and so on.
Note: the first number of a Guthrie sequence is always the number that generated the sequence and the
last number is always 1.

Write a function named isGuthrieSequence which returns 1 if the elements of the array form a
Guthrie sequence. Otherwise, it returns 0.

If you are programming in Java or C#, the function signature is int isGuthrieSequence(int[ ] a)

If you are programming in C++ or C, the function signature is


int isGuthrieSequence(int a[ ], int len) when len is the number of elements in the array.
Examples

if a is return reason
{8, 4, 2, 1} 1 This is the Guthrie sequence for 8
{8, 17, 4, 1} 0 This is not the Guthrie sequence for 8
{8, 4, 1} 0 Missing the 2
{8, 4, 2} 0 A Guthrie sequence must end with 1

public class isGuthrieSequence{


public static void main(String[] args){
int result = isGuthrieSequence(new int[] {8, 4, 2, 1});
System.out.println(result);
result = isGuthrieSequence(new int[] {8, 17, 4, 1});
System.out.println(result);
result = isGuthrieSequence(new int[] {8, 4, 1});
System.out.println(result);
result = isGuthrieSequence(new int[] {8, 4, 2});
System.out.println(result);
}

static int isGuthrieSequence(int[] a){


int isGuthrieSequence = 0;
int nextSequenceNumber = a[0];
if(a[a.length - 1] == 1){
for(int index = 0; index < a.length; index++){
if(nextSequenceNumber == a[index]){
isGuthrieSequence = 1;
if(a[index] % 2 == 0 ){
nextSequenceNumber = a[index] / 2;
}else{
nextSequenceNumber = a[index] * 3 + 1;
}
}
else{
isGuthrieSequence = 0;
break;
}
}
}
return isGuthrieSequence;
}
}

There are three questions on this exam. You have


two hours to complete it. Please do your own work.
1. The Stanton measure of an array is computed as follows. Count the number of 1’s in the
array. Let this count be n. The Stanton measure is the number of times that n appears in the
array. For example, the Stanton measure of {1, 4, 3, 2, 1, 2, 3, 2} is 3 because 1 occurs 2
times in the array and 2 occurs 3 times.
Write a function named stantonMeasure that returns the Stanton measure of its array
argument.
If you are programming in Java or C#, the function prototype is
int stantonMeasure(int[ ] a)
If you are programming in C++ or C, the function prototype is
int stantonMeasure(int a[ ], int len) where len is the number of elements in the array.

Examples
if a is return reason
{1} 1 1 occurs 1 time, 1 occurs 1 time
{0} 1 1 occurs 0 times, 0 occurs 1 time
{3, 1, 1, 4} 0 1 occurs 2 times, 2 occurs 0 times
{1, 3, 1, 1, 3, 3, 2, 3, 3, 3, 4} 6 1 occurs 3 times, 3 occurs 6 times
{} 0 1 occurs 0 times, 0 occurs 0 times

public class stantonMeasure{


public static void main(String[] args){
int result = stantonMeasure(new int[] {1});
System.out.println(result);
result = stantonMeasure(new int[] {0});
System.out.println(result);
result = stantonMeasure(new int[] {3, 1, 1, 4});
System.out.println(result);
result = stantonMeasure(new int[] {1, 3, 1, 1, 3, 3, 2, 3, 3, 3, 4});
System.out.println(result);
result = stantonMeasure(new int[] {});
System.out.println(result);
}
static int stantonMeasure(int[] a){
int stantonMeasure = 0;
int occurrencesOfOne = 0;
for(int index = 0; index < a.length; index++){
if(a[index] == 1){
occurrencesOfOne++;
}
}
for(int index = 0; index < a.length; index++){
if(a[index] == occurrencesOfOne){
stantonMeasure++;
}
}
return stantonMeasure;
}
}

2. The sum factor of an array is defined to be the number of times that the sum of the array
appears as an element of the array. So the sum factor of {1, -1, 1, -1, 1, -1, 1} is 4 because
the sum of the elements of the array is 1 and 1 appears four times in the array. And the sum
factor of {1, 2, 3, 4} is 0 because the sum of the elements of the array is 10 and 10 does not
occur as an element of the array. The sum factor of the empty array { } is defined to be 0.
Write a function named sumFactor that returns the sum factor of its array argument.
If you are programming in Java or C#, the function signature is int sumFactor(int[ ]
a)
If you are programming in C++ or C, the function signature is
int sumFactor(int a[ ], int len) where len is the number of elements in the array.

Examples:
if a is return reason
{3, 0, 2, -5, 0} 2 The sum of array is 0 and 0 occurs 2 times
{9, -3, -3, -1, -1} 0 The sum of the array is 1 and 1 does not occur in array.
{1} 1 The sum of the array is 1 and 1 occurs once in the array
{0, 0, 0} 3 The sum of the array is 0 and 0 occurs 3 times in the array

public class sumFactor{


public static void main(String[] args){
int result = sumFactor(new int[] {3, 0, 2, -5, 0});
System.out.println(result);
result = sumFactor(new int[] {9, -3, -3, -1, -1});
System.out.println(result);
result = sumFactor(new int[] {1});
System.out.println(result);
result = sumFactor(new int[] {0, 0, 0});
System.out.println(result);
}

static int sumFactor(int[] a){


int sumFactor = 0;
int sum = 0;
for(int index = 0; index < a.length; index++){
sum += a[index];
}
for(int index = 0; index < a.length; index++){
if(a[index] == sum){
sumFactor++;
}
}
return sumFactor;
}
}

3. Consider the following algorithm Start with a positive number n if n is even then divide by 2 if n is
odd then multiply by 3 and add 1 continue this until n becomes 1

The Guthrie index of a positive number n is defined to be how many iterations of the above
algorithm it takes before n becomes 1.

For example, the Guthrie index of the number 7 is 16 because the following sequence is 16 numbers
long. 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1

It is easy to see that this sequence was generated by the above algorithm. Since 7 is odd multiply by
3 and add 1 to get 22 which is the first number of the sequence. Since 22 is even, divide by 2 to get
11 which is the second number of the sequence. 11 is odd so multiply by 3 and add 1 to get 34
which is the third number of the sequence and so on.

Write a function named guthrieIndex which computes the Guthrie index of its argument. Its
signature is int guthrieIndex(int n)
Examples

if n is return sequence
1 0 number is already 1
2 1 1
3 7 10, 5, 16, 8, 4, 2, 1
4 2 2, 1
42 8 21, 64, 32, 16, 8, 4, 2, 1

You may assume that the length of the sequence can be represented by a 32 bit signed integer.

public class guthrieIndex{


public static void main(String[] args){
int result = guthrieIndex(1);
System.out.println(result);
result = guthrieIndex(2);
System.out.println(result);
result = guthrieIndex(3);
System.out.println(result);
result = guthrieIndex(4);
System.out.println(result);
result = guthrieIndex(42);
System.out.println(result);
}

static int guthrieIndex(int n){


int guthrieIndex = 0;
if(n > 1){
while(n != 1){
if(n % 2 == 0){
n = n / 2;
}else{
n = n * 3 + 1;
}
guthrieIndex ++;
}
}
return guthrieIndex;
}
}

There are 3 questions on this test. You have two hours to do it. Please do your
own work.

1. It is a fact that there exist two numbers x and y such that x! + y! = 10!. Write a method named
solve10 that returns the values x and y in an array.

The notation n! is called n factorial and is equal to n * n-1 * n-2 * ... 2 * 1,


e.g., 5! = 5*4*3*2*1= 120.

If you are programming in Java or C#, the function prototype is int[ ] solve10() where the length of
the returned array is 2.

If you are programming in C++ or C, the function prototype is int * solve10() where the length of
the returned array is 2.

Please be sure that the method solve10 returns an array, a, with two elements where a[0] = x, a[1] =
y and x! + y! = 10!.

public class solve10{


public static void main(String[] args){
int[] result = solve10();
for(int number : result){
System.out.println(number);
}
}

static int[] solve10(){


int solve10[] = new int[2];
int tenFactorial = 1;
int x = 0;
int y = 0;
boolean factorialFound = false;
for(int i = 1; i <= 10; i++){
tenFactorial = tenFactorial * i;
}
for(x = 0; x < 10; x++){
int xFactorial = 1;
if(x > 0){
for(int i = 1; i <= x; i++){
xFactorial = xFactorial * i;
}
}
for(y = 0; y < 10; y++){
int yFactorial = 1;
if(y > 0){
for(int j = 1; j <= y; j++){
yFactorial = yFactorial * j;
}
}
if(xFactorial + yFactorial == tenFactorial){
factorialFound = true;
break;
}
}
if(factorialFound){
break;
}
}
if(x == 10 && y == 10){
//Not Found
x = 0;
y = 0;
}
solve10[0] = x;
solve10[1] = y;
return solve10;
}
}

2. An array can hold the digits of a number. For example the digits of the number
32053 are stored in the array {3, 2, 0, 5, 3}. Write a method call repsEqual
that takes an array and an integer and returns 1 if the array contains only
the digits of the number in the same order that they appear in the number.
Otherwise it returns 0.

If you are programming in Java or C#, the function prototype is int


repsEqual(int[ ] a, int n)

If you are programming in C++ or C, the function prototype is


int repsEqual(int a[ ], int len, int n) where len is the number of elements in the
array.

Examples (note: your program must work for all values of a and n, not just
those given here!)

if a is and n is return reason


{3, 2, 0, 5, 3} 32053 1 the array contains only the digits of the number, in the same
order as they are in the number.
{3, 2, 0, 5} 32053 0 the last digit of the number is missing from the array.
{3, 2, 0, 5, 3, 4} 32053 0 an extra number (4) is in the array.
{2, 3, 0, 5, 3} 32053 0 the array elements are not in the same order as the digits of the
number
{9, 3, 1, 1, 2} 32053 0 elements in array are not equal to digits of number.
{0, 3, 2, 0, 5, 3} 32053 1 you can ignore leading zeroes.
public class repsEqual{
public static void main(String[] args){
int result = repsEqual(new int[] {3, 2, 0, 5, 3}, 32053);
System.out.println(result);
result = repsEqual(new int[] {3, 2, 0, 5}, 32053);
System.out.println(result);
result = repsEqual(new int[] {3, 2, 0, 5, 3, 4}, 32053);
System.out.println(result);
result = repsEqual(new int[] {2, 3, 0, 5, 3}, 32053);
System.out.println(result);
result = repsEqual(new int[] {9, 3, 1, 1, 2}, 32053);
System.out.println(result);
result = repsEqual(new int[] {0, 3, 2, 0, 5, 3}, 32053);
System.out.println(result);
}

static int repsEqual(int[] a, int n){


int repsEqual = 0;
for(int lastIndex = a.length - 1; lastIndex >= 0 ; lastIndex--){
int lastDigit = n % 10;
n = n / 10;
if(lastDigit == a[lastIndex]){
repsEqual = 1;
}else{
repsEqual = 0;
break;
}
}
return repsEqual;
}
}

3. An array is called centered-15 if some consecutive sequence of elements of the


array sum to 15 and this sequence is preceded and followed by the same number
of elements. For example{3, 2, 10, 4, 1, 6, 9} is centered-15 because the
sequence 10, 4, 1 sums to 15 and the sequence is preceded by two elements (3,
2) and followed by two elements(6,9).

Write a method called isCentered15 that returns 1 if its array argument is


centered-15, otherwise it returns 0.

If you are programming in Java or C#, the function prototype is int


isCentered15(int[ ] a)

If you are programming in C++ or C, the function prototype is


int isCentered5(int a[ ], int len) where len is the number of elements in the array.

Examples
if a is return reason
{3, 2, 10, 4, 1, 6, 9} 1 the sequence 10, 4, 1 sums to 15 and is
preceded by 2 elements and followed by 2
elements. Note that there is another sequence
that sums to 15 (6,9}. It is okay for the array to
have more than one sequence that sums to 15 as
long as at least one of them is centered.

{2, 10, 4, 1, 6, 9} 0 (10, 4, 1) is preceded by one element but


followed by two.
(9,6) is preceded by five elements but followed
by none. Hence neither qualify as centered.
{3, 2, 10, 4, 1, 6} 0 (10, 4, 1) is preceded by two elements but
followed by one. Note that the values 3, 2, 4, 6
sum to 15 but they are not consecutive.
{1,1,8, 3, 1, 1} 1 The entire array sums to 15, hence the
sequence is preceded by zero elements and
followed by zero elements.
{9, 15, 6} 1 the sequence (15) is preceded by one element
and followed by one element.
{1, 1, 2, 2, 1, 1} 0 no sequence sums to 15.

{1, 1, 15 -1,-1} 1 there are three different sequences that sum to


15, the entire array, (1, 15, -1) and (15). In this
case they all are centered but the requirement
is that just one of them has to be.

public class isCentered15{


public static void main(String[] args){
int result = isCentered15(new int[] {3, 2, 10, 4, 1, 6, 9});
System.out.println(result);
result = isCentered15(new int[] {2, 10, 4, 1, 6, 9});
System.out.println(result);
result = isCentered15(new int[] {3, 2, 10, 4, 1, 6});
System.out.println(result);
result = isCentered15(new int[] {1, 1, 8, 3, 1, 1});
System.out.println(result);
result = isCentered15(new int[] {9, 15, 6});
System.out.println(result);
result = isCentered15(new int[] {1, 1, 2, 2, 1, 1});
System.out.println(result);
result = isCentered15(new int[] {1, 1, 15, -1, -1});
System.out.println(result);
}

static int isCentered15(int[] a){


int isCentered15 = 0;
int lowerIndex = 0;
int upperIndex = 0;
int sum = 0;
if(a.length % 2 == 0){
lowerIndex = (a.length / 2) - 1;
upperIndex = a.length / 2 ;
}else{
lowerIndex = (a.length - 1) / 2;
upperIndex = lowerIndex;
}
while(lowerIndex >= 0 && upperIndex < a.length){
sum = 0;
for(int index = lowerIndex; index <= upperIndex;
index++){
sum += a[index];
}
if(sum == 15){
isCentered15 = 1;
break;
}
lowerIndex--;
upperIndex++;
}
return isCentered15;
}
}

There are three questions on this test. You have two hours to finish
it. Please do your own work.
1. A perfect number is one that is the sum of its factors, excluding itself. The 1st perfect number is 6
because 6 = 1 + 2 +3. The 2nd perfect number is 28 which equals 1 + 2 + 4 + 7 + 14. The third is 496 =
1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248. In each case, the number is the sum of all its factors
excluding itself.

Write a method named henry that takes two integer arguments, i and j and returns the sum of
the ith and jth perfect numbers. So for example, henry (1, 3) should return 502 because 6 is the
1st perfect number and 496 is the 3rd perfect number and 6 + 496 = 502.
The function signature is int henry (int i, int j)

You do not have to worry about integer overflow, i.e., you may assume that each sum that
you have to compute can be represented as a 31 bit integer. Hint: use modulo arithmetic to
determine if one number is a factor of another.

public class henry{


public static void main(String[] args){
int result = henry(1, 3);
System.out.println(result);
}
static int henry(int i, int j){
int henry = 0;
int max = Integer.MAX_VALUE;
int perfectCount = 0;
for(int number=1; number <= max; number++){
int sum = 0;
for(int divider = 1; divider < number; divider++){
if(number % divider == 0){
sum += divider;
}
}
if(sum == number){
perfectCount++;
if(perfectCount == i){
henry += sum;
}else if(perfectCount == j){
henry += sum;
break;
}
}
}
return henry;
}
}

2. Write a method named isDivisible that takes an integer array and a divisor and returns 1 if all its
elements are divided by the divisor with no remainder. Otherwise it returns 0.

If you are programming in Java or C#, the function signature is int isDivisible(int [ ] a, int divisor)

If you are programming in C or C++, the function signature is int isDivisible(int a[ ], int len, int
divisor) where len is the number of elements in the array.

Examples

if a is and divisor is return because


{3, 3, 6, 36} 3 1 all elements of a are divisible by 3 with no
remainder.
{4} 2 1 all elements of a are even
{3, 4, 3, 6, 36} 3 0 because when a[1] is divided by 3, it leaves a
remainder of 1
{6, 12, 24, 36} 12 0 because when a[0] is divided by 12, it leaves a
remainder of 6.
{} anything 1 because no element fails the division test.
public class isDivisible{
public static void main(String[] args){
int result = isDivisible(new int[] {3, 3, 6, 36}, 3);
System.out.println(result);
result = isDivisible(new int[] {4}, 2);
System.out.println(result);
result = isDivisible(new int[] {3, 4, 3, 6, 36}, 3);
System.out.println(result);
result = isDivisible(new int[] {6, 12, 24, 36}, 12);
System.out.println(result);
result = isDivisible(new int[] {}, 3);
System.out.println(result);
}

static int isDivisible(int[] a, int divisor){


int isDivisible = 1;
for(int index = 0; index < a.length; index++){
if(a[index] % divisor != 0){
isDivisible = 0;
break;
}
}
return isDivisible;
}
}

3. An array is defined to be n-unique if exactly one pair of its elements sum to n. For example,
the array {2, 7, 3, 4} is 5- unique because only a[0] and a[2] sum to 5. But the array {2, 3, 3, 7}
is not 5-unique because a[0] + a[1] = 5 and a[0] + a[2] = 5.
Write a function named isNUnique that returns 1 if its integer array argument is n-unique,
otherwise it returns 0. So isNUnique(new int[ ]{2, 7, 3, 4}, 5) should return 1 and
isNUnique(new int[] {2, 3, 3, 7}, 5) should return 0.

If you are programming in Java or C#, the function signature is int isNUnique(int[ ] a, int n)

If you are programming in C or C++, the function signature is int isNUnique(int a[ ], int len, int n) where
len is the number of elements in the array.

Examples
If a is and n is return because
{7, 3, 3, 2, 4} 6 0 because a[1]+a[2] == 6 and a[3]+a[4] also == 6.
{7, 3, 3, 2, 4} 10 0 because a[0]+a[1] == 10 and a[0] + a[2] also == 10
{7, 3, 3, 2, 4} 11 1 because only a[0] + a[4] sums to 11
{7, 3, 3, 2, 4} 8 0 because no pair of elements sum to 8. (Note that
a[1]+a[2]+a[3] do sum to 8 but the requirement is that two
elements sum to 8.)
{7, 3, 3, 2, 4} 4 0 no pair of elements sum to 4. (Note that the a[4]==4, but
the requirement is that two elements have to sum to 4.)
{1} anything 0 array must have at least 2 elements
public class isNUnique{
public static void main(String[] args){
int result = isNUnique(new int[] {7, 3, 3, 2, 4}, 6);
System.out.println(result);
result = isNUnique(new int[] {7, 3, 3, 2, 4}, 10);
System.out.println(result);
result = isNUnique(new int[] {7, 3, 3, 2, 4}, 11);
System.out.println(result);
result = isNUnique(new int[] {7, 3, 3, 2, 4}, 8);
System.out.println(result);
result = isNUnique(new int[] {7, 3, 3, 2, 4}, 4);
System.out.println(result);
result = isNUnique(new int[] {1}, 6);
System.out.println(result);
}

static int isNUnique(int[] a, int n){


int isNUnique = 0;
if(a.length > 2){
for(int index = 0; index < a.length; index++){
for(int innerIndex = index+1; innerIndex <
a.length; innerIndex++){
if(a[index]+a[innerIndex] == n){
if(isNUnique == 0){
isNUnique = 1;
}else{
isNUnique = 2;
break;
}
}
}
if(isNUnique == 2){
isNUnique = 0;
break;
}
}
}
return isNUnique;
}
}
There are three questions on this exam. You have two hours to complete it.
1. Write a function named isSquare that returns 1 if its integer argument is a square of some integer,
otherwise it returns 0. Your function must not use any function or method (e.g. sqrt) that comes with a
runtime library or class library!

The signature of the function is int isSquare(int n)

Examples:
if n is return reason
4 1 because 4 = 2*2
25 1 because 25 = 5*5
-4 0 because there is no integer that when squared equals -4. (note, -2 squared
is 4 not -4)
8 0 because the square root of 8 is not an integer.
0 1 because 0 = 0*0

public class isSquare{


public static void main(String[] args){
int result = isSquare(4);
System.out.println(result);
result = isSquare(25);
System.out.println(result);
result = isSquare(-4);
System.out.println(result);
result = isSquare(8);
System.out.println(result);
result = isSquare(0);
System.out.println(result);
}

static int isSquare(int n){


int isSquare = 0;
for(int i = 0; i <= n; i++){
if(i * i == n){
isSquare = 1;
break;
}
}
return isSquare;
}
}

2. A number with a base other than 10 can be written using its base as a subscript. For
example, 10112 represents the binary number 1011 which can be converted to a base 10
number as follows:
(1 * 20) + (1 * 21) + (0 * 22) + (1 * 23) = 1 + 2 + 0 + 8 = 1110

Similarily, the base 3 number 1123 can be converted to base 10 as follows: (2 * 30) + (1 * 31) + (1 * 32) =
2 + 3 + 9 = 1410
And the base 8 number 3258 can be converted to base 10 as follows: (5 * 80) + (2 * 81) + (3 * 82) = 5 + 16
+ 192 = 21310

Write a method named isLegalNumber that takes two arguments. The first argument is
an array whose elements are the digits of the number to test. The second argument is
the base of the number represented by the first argument. The method returns 1 if the
number represented by the array is a legal number in the given base, otherwise it
returns 0.

For example the number 3214 can be passed to the method as follows: isLegalNumber(new int[] {3, 2, 1},
4) This call will return 1 because 3214 is a legal base 4 number.

However, since all digits of a base n number must be less than n, the following call will return 0 because
3716 is not a legal base 6 number (the digit 7 is not allowed) isLegalNumber(new int[] {3, 7, 1}, 6)

If you are programming in Java or C#, the signature of the method is int isLegalNumber(int[ ]
a, int base)
If you are programming in C or C++, the signature of the method is int isLegalNumber(int a[ ],
int len, int base) where len is the size of the array.

int isLegalNumber(int[ ] a, int base)


{
int isLegalNumber = 1;
for(int i = 0; i<a.length; i++)
{
if(a[i]>base)
{
isLegalNumber = 0;
break;
}
}
return isLegalNumber;
}

3. Using the <array, base> representation for a number described in the second question write a
method named convertToBase10 that converts its <array, base> arguments to a base 10
number if the input is legal for the specified base. If it is not, it returns -1.

Some examples:

convertToBase10(new int[ ] {1, 0, 1, 1}, 2) returns 11


convertToBase10(new int[ ] {1, 1, 2}, 3) returns 14
convertToBase10(new int[ ] {3, 2, 5}, 8) returns 213
convertToBase10 (new int[ ] {3, 7, 1}, 6) returns 0 because 371 is not a legal base 6 number.
Your convertToBase10 method must call the isLegalNumber method that you wrote for question 2.

If you are programming in Java or C#, the function signature is: int convertToBase10(int[ ] a, int base)

If you are programming in C or C++, the function signature is: int convertToBase10(int a[ ], int len, int
base) where len is the size of the array.

static int convertToBase10(int[] a, int base)


{
int convertToBase10=0;
int count = 0;
if(isLegalNumber(a,base) == 0)
convertToBase10 = -1;
else
{
for(int i = a.length -1; i>=0; i--)
{
convertToBase10 += a[i]*findPower(base, count);
count++;
}
}
return convertToBase10;
}
int findPower(int b, int p)
{
int pow = 1;
if(p == 0)
pow = 1;
else{
for(int i = 1; i<=p;i++)
{
pow *=b;
}
}
return pow;
}
int isLegalNumber(int[ ] a, int base)
{
int isLegalNumber = 1;
for(int i = 0; i<a.length; i++)
{
if(a[i]>base)
{
isLegalNumber = 0;
break;
}
}
return isLegalNumber;
}
package com.knight.exam.java.nonZeroArray;

/**
* Created by sachinkeshav on 12/30/14.
*/
public class NonZeroArray {

public static void main(String[] args) {


System.out.println(arrayHasNoZeros(new int[]{1, 2, 3}));
System.out.println(arrayHasNoZeros(new int[]{1, 0, 4, 0}));
System.out.println(arrayHasNoZeros(new int[]{1, 2, 3, 0}));
System.out.println(arrayHasNoZeros(new int[]{0, 0, 0}));
System.out.println(arrayHasNoZeros(new int[]{}));
}

static int arrayHasNoZeros(int[] a) {


for (int anA : a) {
if (anA == 0) {
return 0;
}
}

return 1;
}
}
public class ComputeDepth {

public static void main(String[] args) {


System.out.println(computeDepth(42));
System.out.println(computeDepth(7));
System.out.println(computeDepth(13));
System.out.println(computeDepth(25));
}

static int computeDepth(int n) {

boolean[] flags = new boolean[10];


for (int i = 0; i < 10; i++) flags[i] = false;
int index = 1;
while (true) {
int product = n * index;
while (product > 0) {
int rem = product % 10;
product /= 10;

if (!flags[rem]) {
flags[rem] = true;
}
}

boolean finalFlag = true;


for (boolean aFlag : flags) {
if (!aFlag)
finalFlag = false;
}

if (finalFlag) break;
index++;
}

return index;
}
}

There are 3 questions on this test. You have 2 hours to


finish it. Please use tabs or spaces to indent your program.
1. A simple pattern match on the elements of an array A can be defined using another array P.
Each element n of P is negative or positive (never zero) and defines the number of elements
in a sequence in A. The first sequence in A starts at A[0] and its length is defined by P[0].
The second sequence follows the first sequence and its length is defined by P[1] and so on.
Furthermore, for n in P, if n is positive then the sequence of n elements of A must all be
positive. Otherwise the sequence of abs(n) elements must all be negative. The sum of the
absolute values of the elements of P must be the length of A.

For example, consider the array A = {1, 2, 3, -5, -5, 2, 3, 18} If P = {3, -2, 3} then A
matches P because
i. the first 3 elements of A (1, 2, 3) are positive (P[0] is 3 and is
positive),
ii. the next 2 elements of A (-5, -5) are negative (P[1] is -2 and is
negative)
iii. and the last 3 elements of A (2, 3, 18) are positive (P[2] is 3 and is
positive) Notice that the absolute values of the elements of P sum to
8 which is the length of A.

The array A also matches the following patterns( that is P can be of the
followings):
P ={2, 1, -1, -1, 2, 1}, P ={1, 2, -1, -1, 1, 2}, P={2, 1, -2, 3}, P={1, 1, 1, -
1, -1, 1, 1, 1}
In each case the sum of the absolute values is 8, which is the length of A and each sequence of numbers in
A defined in a pattern is negative or positive as required.
The array A = {1, 2, 3, -5, -5, 2, 3, 18} does not match the following patterns:

i. P = {4, -1, 3} (because the first 4 elements of A are not positive (A[3] is
negative) as required by P)
ii. P = {2, -3, 3} (because even though the first 2 elements of A are positive, the
next 3 are required to be negative but A[2] is positive which does not
satisfy this requirement.)
iii. P = {8} (because this requires all elements of A to be positive and they are
not.)

Please note: Zero is neither positive nor negative.

Write a function named matches which takes arrays A and P as arguments and returns 1 if A
matches P. Otherwise it returns 0. You may assume that P is a legal pattern, i.e., the absolute
value of its elements sum to the length of A and it contains no zeros. So do not write code to
check if P is legal!
If you are programming in Java or C# the signature of the function is
int matches(int[ ] a, int[ ] p)

If you are programming in C++ or C, the signature of the function is


int matches(int a[ ], int len, int p[ ]) where len is the number of elements of a.
Furthermore, the value of p[0] should be the length of p. So, for example, if p={5, 2, -1,
-2, 4}, p[0]=5 means that the array has 5 elements and that the last 4 define the pattern.

Hint: Your function should have one loop nested in another.

The outer loop iterates through the elements of P. The inner loop iterates through the
next sequence of A. The upper bound of the inner loop is the absolute value of the
current element of P. The lower bound of the inner loop is 0. The loop variable of the
inner loop is not used to index A!
public class matches {
static int matches(int[] a, int[] pattern) {

int matches = 1;
int arrayAIndex = 0;

for(int outerIndex = 0; outerIndex < pattern.length;


outerIndex++) {
for(int index = 0; index < Math.abs(pattern[outerIndex]);
index++) {
if(pattern[outerIndex] > 0) {

if(a[arrayAIndex++ ] < 0 && arrayAIndex < a.length) {


matches = 0;
break;
}
}
else {
if(a[arrayAIndex++ ]>0 &&arrayAIndex< a.length) {
matches = 0;
break;
}
}

if(matches == 0)
break;
}

return matches;
}

public static void main(String[] args) {


System.out.println(matches(new int[]{1, 2, 3, -5, -5, 2, 3,
18}, new int[]{3, -2, 3} ));
System.out.println(matches(new int[]{1, 2, 3, -5, -5, 2, 3,
18}, new int[]{2, 1, -1, -1, 2, 1} ));
System.out.println(matches(new int[]{1, 2, 3, -5, -5, 2, 3,
18}, new int[]{1, 2, -1, -1, 1, 2} ));
System.out.println(matches(new int[]{1, 2, 3, -5, -5, 2, 3,
18}, new int[]{2, 1, -2, 3} ));
System.out.println(matches(new int[]{1, 2, 3, -5, -5, 2, 3,
18}, new int[]{1, 1, 1, -1, -1, 1, 1, 1} ));
System.out.println(matches(new int[]{1, 2, 3, -5, -5, 2, 3,
18}, new int[]{1, 1, 1, -1, -1, 1, 1, 1} ));
System.out.println(matches(new int[]{1, 2, 3, -5, -5, 2, 3,
18}, new int[]{4, -1, 3} ));
System.out.println(matches(new int[]{1, 2, 3, -5, -5, 2, 3,
18}, new int[]{2, -3, 3} ));
System.out.println(matches(new int[]{1, 2, 3, -5, -5, 2, 3,
18}, new int[]{8} ));

}
public class PatternMatcher {

public static void main(String[] args) {


System.out.println(matchPattern(new int[]{1, 1, 1, 2, 2, 1, 1, 3}, new int[]{1,
2, 1, 3}));
System.out.println(matchPattern(new int[]{1, 1, 1, 1, 1}, new
int[]{1}));
System.out.println(matchPattern(new int[]{1}, new int[]{1}));
System.out.println(matchPattern(new int[]{1, 1, 2, 2, 2, 2}, new
int[]{1, 2}));
System.out.println(matchPattern(new int[]{1, 2, 3}, new
int[]{1, 2}));
System.out.println(matchPattern(new int[]{1, 2}, new int[]{1,
2, 3}));
System.out.println(matchPattern(new int[]{1, 1, 2, 2, 2, 2, 3}, new
int[]{1, 3}));
System.out.println(matchPattern(new int[]{1, 1, 1, 1}, new
int[]{1, 2}));
System.out.println(matchPattern(new int[]{1, 1, 1, 1, 2, 2, 3, 3}, new
int[]{1, 2}));
System.out.println(matchPattern(new int[]{1, 1, 10, 4, 4, 3}, new
int[]{1, 4, 3}));
}

static int matchPattern(int[] a, int[] pattern) {


int i = 0;
int k = 0;
int matches = 0;

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


if (a[i] == pattern[k])
matches++;

else if (matches == 0 || k == pattern.length - 1)


return 0;
else {
k++;
if (a[i] == pattern[k])
matches++;
else return 0;
}
}

if (i == a.length && k == pattern.length - 1) return 1;


else return 0;
}
}
2. Define a stacked number to be a number that is the sum of the first n positive integers for
some n. The first 5 stacked numbers are
1=1
3 = 1 +2
6=1+2+3
10 = 1 + 2 + 3+ 4
15 = 1 + 2 + 3 + 4 + 5
Note that from the above we can deduce that 7, 8, and 9 are not stacked numbers because they cannot be
the sum of any sequence of positive integers that start at 1.
Write a function named isStacked that returns 1 if its argument is stacked. Otherwise it returns 0. Its
signature is: int isStacked(int n);
So for example, isStacked(10) should return 1 and isStacked(7) should return 0.
package com.knight.exam.java.stackedNumber;

/**
* Created by sachinkeshav on 12/31/14.
*/
public class StackedNumber {

public static void main(String[] args) {


System.out.println(isStacked(1));
System.out.println(isStacked(3));
System.out.println(isStacked(6));
System.out.println(isStacked(10));
System.out.println(isStacked(15));
System.out.println(isStacked(7));
}

static int isStacked1(int n) {


int index = 1;
int sum = 1;
while (true) {
if (n == sum)
return 1;

if (sum > n)
return 0;

index++;
sum += index;
}
}

static int isStacked(int n) {


int number = 1;
int sum = 0;
while (sum < n) {
sum += number;
number++;
}
if (sum == n) return 1;
return 0;
}
}

3. Define an array to be sum-safe if none of its elements is equal to the sum of its elements. The
array a = {5, -5, 0} is not sum-safe because the sum of its elements is 0 and a[2] == 0.
However, the array a ={5, -2, 1} is sum-safe because the sum of its elements is 4 and none of
its elements equal 4.
Write a function named isSumSafe that returns 1 if its argument is sum-safe, otherwise it returns 0.
If you are writing in Java or C#, the function signature is int isSumSafe(int[ ]a)
If you are writing in C++ or C, the function signature is int isSumSafe(int a[ ], int len) where len is the number of
elements in a.
For example, isSumSafe(new int[ ] {5, -5, 0}) should return 0 and isSumSafe(new int[ ]{5, -2, 1}) should
return 1. Return 0 if the array is empty.

public class SumSafe {

public static void main(String[] args) {


System.out.println(isSumSafe(new int[]{5, -5, 0}));
System.out.println(isSumSafe(new int[]{5, -2, 1}));
System.out.println(isSumSafe(new int[]{}));
}

static int isSumSafe(int[] a) {


if (a.length == 0) return 0;

int sum = 0;

for (int anA : a) {


sum += anA;
}

for (int anA : a) {


if (anA == sum)
return 0;
}

return 1;
}
}
There are three questions on this exam. You have two
hours to finish. Please do your own work.
1. Define a positive number to be isolated if none of the digits in its square are in its cube. For example
163 is n isolated number because 69*69 = 26569 and 69*69*69 = 4330747 and the square does not
contain any of the digits 0, 3, 4 and 7 which are the digits used in the cube. On the other hand 162 is
not an isolated number because 162*162=26244 and 162*162*162 = 4251528 and the digits 2 and 4
which appear in the square are also in the cube.

Write a function named isIsolated that returns 1 if its argument is an isolated number, it returns 0 if its
not an isolated number and it returns -1 if it cannot determine whether it is isolated or not (see the note
below). The function signature is:

int isIsolated(long n)

Note that the type of the input parameter is long. The maximum positive number that can be represented
as a long is 63 bits long. This allows us to test numbers up to 2,097,151 because the cube of 2,097,151
can be represented as a long. However, the cube of 2,097,152 requires more than 63 bits to represent it
and hence cannot be computed without extra effort. Therefore, your function should test if n is larger than
2,097,151 and return -1 if it is. If n is less than 1 your function should also return -1.

Hint: n % 10 is the rightmost digit of n, n = n/10 shifts the digits of n one place to the right.

The first 10 isolated numbers are


N n*n n*n*n
2 4 8
3 9 27
8 64 512
9 81 729
14 196 2744
24 576 13824
28 784 21952
34 1156 39304
58 3364 195112
63 3969 250047

public class IsolatedNumber {

public static void main(String[] args) {


System.out.println(isIsolated(69));
System.out.println(isIsolated(163));
System.out.println(isIsolated(162));
System.out.println(isIsolated(2));
System.out.println(isIsolated(3));
System.out.println(isIsolated(8));
System.out.println(isIsolated(9));
System.out.println(isIsolated(14));
System.out.println(isIsolated(24));
System.out.println(isIsolated(28));
System.out.println(isIsolated(34));
System.out.println(isIsolated(58));
System.out.println(isIsolated(63));
}

static int isIsolated(long n) {


if (n >= 2097151 || n < 1) return -1;

long square = n * n;
long cube = n * n * n;
while (cube > 0) {
long cubeDigit = cube % 10;
cube /= 10;

long tempSquare = square;


while (tempSquare > 0) {
long squareDigit = tempSquare % 10;
tempSquare /= 10;

if (squareDigit == cubeDigit)
return 0;
}
}

return 1;
}
}

2. An array is called vanilla if all its elements are made up of the same digit. For example {1, 1, 11,
1111, 1111111} is a vanilla array because all its elements use only the digit 1. However, the array {11,
101, 1111, 11111} is not a vanilla array because its elements use the digits 0 and 1. Write a method
called isVanilla that returns 1 if its argument is a vanilla array. Otherwise it returns 0.

If you are writing in Java or C#, the function signature is int isVanilla(int[ ] a)

If you are writing in C or C++, the function signature is int isVanilla(int a[ ], int len) where len is the
number of elements in the array a. Example
if a is Return reason
{1} 1 all elements use only digit 1.
{11, 22, 13, 34, 125} 0 Elements used 5 different digits
{9, 999, 99999, -9999} 1 Only digit 9 is used by all
elements. Note that negative
numbers are okay.
{} 1 There is no counterexample to
the hypothesis that all elements
use the
public class VanillaArray { same digit.

public static void main(String[] args) {


System.out.println(isVanilla(new int[]{1, 1, 11, 1111,
1111111}));
System.out.println(isVanilla(new int[]{11, 101, 1111,
11111}));
System.out.println(isVanilla(new int[]{11, 222, 1111,
11111}));
System.out.println(isVanilla(new int[]{1}));
System.out.println(isVanilla(new int[]{11, 22, 13, 34, 125}));
System.out.println(isVanilla(new int[]{9, 999, 99999, -
9999}));
System.out.println(isVanilla(new int[]{}));
}

static int isVanilla1(int[] a) {


for (int anA : a) {
anA = anA < 0 ? -anA : anA;
int digit = anA % 10;
while (anA > 0) {
int remainder = anA % 10;

if (digit != remainder)
return 0;
anA /= 10;
}
}

return 1;
}

static int isVanilla(int[] a) {


if (a.length == 0)
return 1;

int digit = a[0] % 10;

for (int anA : a) {


anA = anA < 0 ? -anA : anA;
while (anA > 0) {
int d = anA % 10;
anA /= 10;
if (d != digit)
return 0;
}
}
return 1;
}
}
3. Define an array to be trivalent if all its elements are one of three different values. For example, {22,
19, 10, 10, 19, 22, 22, 10} is trivalent because all elements are either 10, 22, or 19. However, the
array {1, 2, 2, 2, 2, 2, 2} is not trivalent because it contains only two different values (1, 2). The array
{2, 2, 3, 3, 3, 3, 2, 41, 65} is not trivalent because it contains four different values (2, 3, 41, 65).

Write a function named isTrivalent that returns 1 if its array argument is trivalent, otherwise it returns 0.

If you are writing in Java or C#, the function signature is int isTrivalent (int[ ] a)

If you are writing in C or C++, the function signature is int isTrivalent(int a[ ], int len) where len is the number of
elements in the array a.

Hint: Remember that the elements of the array can be any value, so be careful how you initialize
your local variables! For example using -1 to initialize a variable won’t work because -1 might be
one of the values in the array.

Examples

if a is return Reason
{-1, 0, 1, 0, 0, 0} 1 All elements have one of three values (0, -1, 1)
{} 0 There are no elements
{ 2147483647, -1, -1 1 Again only three different values. Note that the value of a[0]
-2147483648} is the maximum integer and the value of a[3]m is the minimu
integer so you can’t use those to initialize local variables.
public class TrivalentArray {

public static void main(String[] args) {


System.out.println(isTrivalent(new int[]{22, 19, 10, 10, 19,
22, 22, 10}));
System.out.println(isTrivalent(new int[]{1, 2, 2, 2, 2, 2,
2}));
System.out.println(isTrivalent(new int[]{2, 2, 3, 3, 3, 3, 2,
41, 65}));
System.out.println(isTrivalent(new int[]{-1, 0, 1, 0, 0, 0}));
System.out.println(isTrivalent(new int[]{}));
System.out.println(isTrivalent(new int[]{2147483647, -1, -1, -
2147483648}));
}

static int isTrivalent(int[] a) {

int[] tempArray = new int[a.length];


for (int i = 0; i < tempArray.length; i++)
tempArray[i] = Integer.MIN_VALUE;

int index = 0;
for (int anA : a) {
boolean flag = true;
for (int k = 0; k < index; k++) {
if (tempArray[k] == anA) {
flag = false;
break;
} else {
flag = true;
}
}

if (flag) {
tempArray[index] = anA;
index++;
}
}

if (index != 3) return 0;
else return 1;
}
}

There are 3 questions on this exam. You have 2 hours to complete it.
Please do your own work and use indentation.
1. Write a function named countRepresentations that returns the number of ways that an amount of
money in rupees can be represented as rupee notes. For this problem we only use rupee notes in
denominations of 1, 2, 5, 10 and 20 rupee notes.

The signature of the function is: int countRepresentations(int numRupees)

For example, countRepresentations(12) should return 15 because 12 rupees can be represented in


the following 15 ways.

1. 12 one rupee notes


2. 1 two rupee note plus 10 one rupee notes
3. 2 two rupee notes plus 8 one rupee notes
4. 3 two rupee notes plus 6 one rupee notes
5. 4 two rupee notes plus 4 one rupee notes
6. 5 two rupee notes plus 2 one rupee notes
7. 6 two rupee notes
8. 1 five rupee note plus 7 one rupee notes
9. 1 five rupee note, 1 two rupee note and 5 one rupee notes
10. 1 five rupee note, 2 two rupee notes and 3 one rupee notes
11. 1 five rupee note, 3 two notes and 1 one rupee note
12. 2 five rupee notes and 2 one rupee notes
13. 2 five rupee notes and 1 two rupee note
14. 1 ten rupee note and 2 one rupee notes
15. 1 ten rupee note and 1 two rupee note
Hint: Use a nested loop that looks like this. Please fill in the blanks intelligently,
i.e. minimize the number of times that the if statement is executed.

for (int rupee20=0; rupee20<= ; rupee20++)


for (int rupee10=0; rupee10<= ; rupee10++)
for (int rupee5=0; rupee5<= ; rupee5++)
for (int rupee2=0; rupee2<= ; rupee2++)
for (int rupee1=0; rupee1<= ; rupee1++)
{
if ( ) count++
}

public class CountRepresentation {

public static void main(String[] args) {


System.out.println(countRepresentations(12));
}

static int countRepresentations(int numRupees) {


int count = 0;
for (int rupee20 = 0; rupee20 <= (numRupees) / 20; rupee20++) {
for (int rupee10 = 0; rupee10 <= (numRupees - (rupee20 * 20)) / 10; rupee10++) {
for (int rupee5 = 0; rupee5 <= (numRupees -(rupee10 * 10 + rupee20 * 20)) / 5;
rupee5++) {
for (int rupee2 = 0; rupee2 <= (numRupees - (rupee5 * 5 + rupee10 * 10 + rupee20 *
20)) / 2; rupee2++) {
for (int rupee1 = 0; rupee1 <= numRupees - (rupee2 * 2 + rupee5 * 5 + rupee10 * 10 +
rupee20 * 20); rupee1++) {
if ((rupee1 + rupee2 * 2 + rupee5 * 5 + rupee10 * 10 + rupee20 * 20) == numRupees)
{
count++;
}
}
}
}
}
}
return count;
}
}

2. An integer array is defined to be sequentially-bounded if it is in ascending order and each value, n, in


the array occurs less than n times in the array. So {2, 3, 3, 99, 99, 99, 99, 99} is sequentially-bounded
because it is in ascending order and the value 2 occurs less than 2 times, the value 3 occurs less than 3
times and the value 99 occurs less than 99 times. On the other hand, the array {1, 2, 3} is not
sequentially-bounded because the value 1 does not occur < 1 times. The array {2, 3, 3, 3, 3} is not
sequentially-bounded because the maximum allowable occurrences of 3 is 2 but 3 occurs 4 times. The
array {12, 12, 9} is not sequentially-bounded because it is not in ascending order.

Write a function named isSequentiallyBounded that returns 1 if its array argument is sequentially-
bounded, otherwise it returns 0.

If you are programming in Java or C#, the function signature is int isSequentiallyBounded(int[ ] a)
If you are programming in C or C++, the function signature is int isSequentiallyBounded(int a[ ], int
len) where len is the length of the array.

Examples

if a is return Reason
{0, 1} 0 the value 0 has to occur less than 0 times, but it doesn’t
{-1, 2} 0 if array contains a negative number, return 0.
{} 1 since there are no values, there are none that can fail the test.
{5, 5, 5, 5} 1 5 occurs less than 5 times
{5, 5, 5, 2, 5} 0 array is not in ascending order.

public class SequentiallyBounded {

public static void main(String[] args) {


System.out.println(isSequentiallyBounded(new int[]{2,3,3,99,99,99,99,99}));
System.out.println(isSequentiallyBounded(new int[]{2, 3, 3, 3, 3}));
System.out.println(isSequentiallyBounded(new int[]{12, 12, 9}));
System.out.println(isSequentiallyBounded(new int[]{0}));
System.out.println(isSequentiallyBounded(new int[]{0, 1}));
System.out.println(isSequentiallyBounded(new int[]{-1, 2}));
System.out.println(isSequentiallyBounded(new int[]{}));
System.out.println(isSequentiallyBounded(new int[]{5, 5, 5, 5}));
System.out.println(isSequentiallyBounded(new int[]{5, 5, 5, 2, 5}));
}

public static int isSequentiallyBounded(int[] a) {


int countSequence = 1;

if (a.length == 1 && a[0] <= 0)


return 0;

for (int index = 0; index < a.length - 1; index++) {


if (a[index] > a[index + 1])
return 0;

if (a[index] == a[index + 1])


countSequence++;
else
countSequence = 1;

if (a[index] <= countSequence)


return 0;
}
return 1;
}

static int isSequentiallyBounded1(int[] a) {


if (a.length == 0)
return 1;
if (a.length == 1 && a[0] == 0)
return 0;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1])
return 0;
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[i] == a[j])
count++;
}
if (count >= a[i])
return 0;
}
return 1;
}
}

3. An array is defined to be minmax-disjoint if the following conditions hold:


a. The minimum and maximum values of the array are not equal.
b. The minimum and maximum values of the array are not adjacent to one another.
c. The minimum value occurs exactly once in the array.
d. The maximum value occurs exactly once in the array.

For example the array {5, 4, 1, 3, 2} is minmax-disjoint because


a. The maximum value is 5 and the minimum value is 1 and they are not equal.
b. 5 and 1 are not adjacent to one another
c. 5 occurs exactly once in the array
d. 1 occurs exactly once in the array

Write a function named isMinMaxDisjoint that returns 1 if its array argument is minmax-disjoint, otherwise it
returns 0.
If you are programming in Java or C#, the function signature is int isMinMaxDisjoint(int[ ] a)

If you are programming in C or C#, the function signature is


int isMinMaxDisjoint(int a[ ], int len) where len is the number of elements in the array. Examples of
arrays that are not minMaxDisjoint

if a is return Reason
{18, -1, 3, 4, 0} 0 The max and min values are
adjacent to one another.
{9, 0, 5, 9} 0 The max value occurs twice in the
array.
{0, 5, 18, 0, 9| 0 The min value occurs twice in the
array.
{7, 7, 7, 7} 0 The min and the max value must
be different.
{} 0 There is no min or max.
{1, 2} 0 The min and max elements are
next to one another.
{1} 0 The min and the max are the
same.
public class MinMaxDisjoint {

public static void main(String[] args) {


System.out.println(isMinMaxDisjoint(new int[]{5, 4, 1, 3,
2}));
System.out.println(isMinMaxDisjoint(new int[]{18, -1, 3, 4,
0}));
System.out.println(isMinMaxDisjoint(new int[]{9, 0, 5, 9}));
System.out.println(isMinMaxDisjoint(new int[]{0, 5, 18, 0,
9}));
System.out.println(isMinMaxDisjoint(new int[]{7, 7, 7, 7}));
System.out.println(isMinMaxDisjoint(new int[]{}));
System.out.println(isMinMaxDisjoint(new int[]{1, 2}));
System.out.println(isMinMaxDisjoint(new int[]{1}));
}

public static int isMinMaxDisjoint(int[] a) {

if (a.length <= 2) return 0;

int minValue = Integer.MAX_VALUE;


int maxValue = Integer.MIN_VALUE;

for (int anA : a) {


if (anA < minValue) {
minValue = anA;
}

if (anA > maxValue) {


maxValue = anA;
}
}

if (minValue == maxValue) return 0;


int minCount = 0;
int maxCount = 0;
for (int i = 0; i < a.length - 1; i++) {
if ((a[i] == minValue && a[i + 1] == maxValue) || (a[i] ==
maxValue && a[i + 1] == minValue)) {
return 0;
} else {
if (a[i] == minValue) minCount++;
if (a[i] == maxValue) maxCount++;
}
if (minCount > 1 || maxCount > 1) return 0;
}

return 1;
}
}
There are 3 questions on this exam. You have 2 hours to complete it. Please do
your own work.
1. The number 124 has the property that it is the smallest number whose first three multiples contain the digit 2.
Observe that 124*1 = 124, 124*2 = 248, 124*3 = 372 and that 124, 248 and 372 each contain the digit 2.
It is possible to generalize this property to be the smallest number whose first n multiples each contain
the digit 2. Write a function named smallest(n) that returns the smallest number whose first n multiples
contain the digit 2. Hint: use modulo base 10 arithmetic to examine digits.

Its signature is int smallest(int n)

You may assume that such a number is computable on a 32 bit machine, i.e, you do not have to detect integer

overflow in your answer. Examples


If n is return because
because the first four multiples of 624 are 624, 1248, 1872, 2496 and they all contain the
4 624
digit 2. Furthermore 624 is the smallest number whose first four multiples contain the digit 2.
because the first five multiples of 624 are 624, 1248, 1872, 2496, 3120. Note that 624 is also
5 624
the smallest number whose first 4 multiples contain the digit 2.
6 642 because the first five multiples of 642 are 642, 1284, 1926, 2568, 3210, 3852
because the first five multiples of 4062 are 4062, 8124, 12186, 16248, 20310, 24372, 28434.
7 4062
Note that it is okay for one of the multiples to contain the digit 2 more than once (e.g., 24372).

package com.knight.exam.java.smallestNDigit;

/**
* Created by sachinkeshav on 1/2/15.
*/
public class SmallestNDigit {

public static void main(String[] args) {


System.out.println(smallest(1));
System.out.println(smallest(2));
System.out.println(smallest(3));
System.out.println(smallest(4));
System.out.println(smallest(5));
System.out.println(smallest(6));
System.out.println(smallest(7));
}

static int smallest(int n) {


int num = 1;
while (true) {
boolean flag = false;
for (int i = 1; i <= n; i++) {
flag = false;
int product = num * i;
while (product > 0) {
int digit = product % 10;
product /= 10;
if (digit == 2) {
flag = true;
break;
}
}
if (!flag)
break;
}
if (flag) return num;
num++;
}
}
}

2. Define a cluster in an integer array to be a maximum sequence of elements that are all the
same value. For example, in the array {3, 3, 3, 4, 4 3, 2, 2, 2, 2, 4} there are 5 clusters, {3, 3,
3}, {4, 4}, {3}, {2, 2, 2, 2} and {4}. A cluster-compression of an array replaces each cluster
with the number that is repeated in the cluster. So, the cluster compression of the previous
array would be {3, 4, 3, 2, 4}. The first cluster {3, 3, 3} is replaced by a single 3, and so on.

Write a function named clusterCompression with the following signature

If you are programming in Java or C#, the function signature is


int[ ] clusterCompression(int[ ] a)

If you are programming in C++ or C, the function signature is


int *clusterCompression(int a[ ], int len) where len is the length of the array.

The function returns the cluster compression of the array a. The length of the returned array
must be equal to the number of clusters in the origin array! This means that someplace in your
answer you must dynamically allocate the returned array.
In Java or C# you can use int[ ] result = new int[numClusters];
In C or C++ you can use int *result = (int *)calloc(numClusters, sizeof(int)); Examples

a is then function returns


{0, 0, 0, 2, 0, 2, 0, 2, 0, 0} {0, 2, 0, 2, 0, 2, 0}
{18} {18}
{} {}
{-5, -5, -5, -5, -5} {-5}
{1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1} {1, 2, 1}
{8, 8, 6, 6, -2, -2, -2} {8, 6, -2}
import java.util.Arrays;
public class ClusterCompression {

public static void main(String[] args) {


System.out.println(Arrays.toString(clusterCompression(new
int[]{3, 3, 3, 4, 4, 3, 2, 2, 2, 2, 4})));
System.out.println(Arrays.toString(clusterCompression(new
int[]{0, 0, 0, 2, 0, 2, 0, 2, 0, 0})));
System.out.println(Arrays.toString(clusterCompression(new
int[]{18})));
System.out.println(Arrays.toString(clusterCompression(new
int[]{})));
System.out.println(Arrays.toString(clusterCompression(new
int[]{-5, -5, -5, -5, -5})));
System.out.println(Arrays.toString(clusterCompression(new
int[]{1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1})));
System.out.println(Arrays.toString(clusterCompression(new
int[]{8, 8, 6, 6, -2, -2, -2})));
}

static int[] clusterCompression(int[] a) {


if (a.length == 0) {
return new int[]{};
}

int numClusters = 1;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] != a[i + 1]) {
numClusters++;
}
}

int[] result = new int[numClusters];

if (numClusters == 1) {
result[0] = a[0];
return result;
}

int clusterIndex = 0;

for (int i = 0; i < a.length - 1; i++) {


if (a[i] != a[i + 1]) {
result[clusterIndex] = a[i];
result[clusterIndex + 1] = a[i + 1];
clusterIndex++;
}
}

return result;
}
}
3. Define an array to be a railroad-tie array if the following three conditions hold

i. The array contains at least one non-zero element


ii. Every non-zero element has exactly one non-zero neighbor
iii. Every zero element has two non-zero neighbors.

For example, {1, 2, 0, 3, -18, 0, 2, 2} is a railroad-tie array because


a[0] = 1 has exactly one non-zero neighbor (a[1])
a[1] = 2 has exactly one non-zero neighbor (a[0])
a[2] = 0 has two non-zero neighbors (a[1] and a[3])
a[3] = 3 has exactly one non-zero neighbor (a[4])
a[4] = -18 has exactly one non-zero neighbor (a[3])
a[5] = 0 has two non-zero neighbors (a[4] and a[6])
a[6] = 2 has exactly one non-zero neighbor (a[7])
a[7] = 2 has exactly one non-zero neighbor (a[6])

The following are not railroad-tie arrays

{1, 2, 3, 0, 2, 2}, because a[1]=2 has two non-zero neighbors.


{0, 1, 2, 0, 3, 4}, because a[0]=0 has only one non-zero neighbor (it has no left neighbor)
{1, 2, 0, 0, 3, 4}, because a[2]=0 has only one non-zero neighbor (a[1])
{1}, because a[0]=1 does not have any non-zero neighbors.
{}, because the array must have at least one non-zero element
{0}, because the array must have at lease one non-zero element.

Write a function named isRailroadTie which returns 1 if its array argument is a railroad-tie array; otherwise it
returns 0.

If you are writing in Java or C#, the function signature is int isRailroadTie(int[ ] a)

If you are writing in C or C++, the function signature is


int isRailroadTie(int a[ ], int len) where len is the number

of elements in the array a More examples:

if a is return
{1, 2} 1
{1, 2, 0, 1, 2, 0, 1, 2} 1
{3, 3, 0, 3, 3, 0, 3, 3, 0, 3, 3} 1
{0, 0, 0, 0} 0 (must have non-zero element)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 0 (a[1] has two non-zero neighbors)
{1, 3, 0, 3, 5, 0} 0 (a[5] has no right neighbor)

public class RailroadTie {

public static void main(String[] args) {


System.out.println(isRailroadTie(new int[]{
1, 2, 0, 3, -18, 0, 2, 2}));
System.out.println(isRailroadTie(new int[]{
1, 2, 3, 0, 2, 2}));
System.out.println(isRailroadTie(new int[]{
0, 1, 2, 0, 3, 4}));
System.out.println(isRailroadTie(new int[]{
1, 2, 0, 0, 3, 4}));
System.out.println(isRailroadTie(new int[]{1}));
System.out.println(isRailroadTie(new int[]{}));
System.out.println(isRailroadTie(new int[]{0}));
System.out.println(isRailroadTie(new int[]{1, 2}));
System.out.println(isRailroadTie(new int[]{
1, 2, 0, 1, 2, 0, 1, 2}));
System.out.println(isRailroadTie(new int[]{
3, 3, 0, 3, 3, 0, 3, 3, 0, 3, 3}));
System.out.println(isRailroadTie(new int[]{0, 0, 0, 0}));
System.out.println(isRailroadTie(new int[]{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10}));
System.out.println(isRailroadTie(new int[]{
1, 3, 0, 3, 5, 0}));
}

static int isRailroadTie(int[] a) {


if (a.length <= 1 || a[0] == 0 || a[(a.length - 1)] == 0)
return 0;

for (int i = 1; i < a.length - 1; i++) {


if (a[i] != 0 && ((a[i + 1] != 0 && a[i - 1] != 0) ||
(a[i + 1] == 0 && a[i - 1] == 0))) {
return 0;
} else if (a[i] == 0 && (a[i - 1] ==0 || a[i + 1] == 0)) {
return 0;
}

}
return 1;
}
}

This exam has three questions. You have two hours to complete it.
Please format your answers so that blocks are indented. This makes it
easier for the grader to read your answers. And do your own work

1. Define the fullness quotient of an integer n > 0 to be the number of representations of n in


bases 2 through 9 that have no zeroes anywhere after the most significant digit.

For example, to see why the fullness quotient of 94 is 6 examine the following table which
shows the representations of 94 in bases 2 through 9.
base representation of 94 because

2 1011110 26 + 24 + 23 + 22 + 21 = 94

3 10111 34 + 32 + 31 + 30 = 94

4 1132 43 + 42 + 3*41 + 2*40 = 94

5 334 3*52 + 3*51 + 4*40 = 94

6 234 2*62 + 3*61 + 4*60 = 94

7 163 1*72 + 6*71 + 3*70 = 94

8 136 1*82 + 3*81 + 6*80 = 94

9 114 1*92 + 1*91 + 4*90 = 94

Notice that the representations of 94 in base 2 and 3 both have 0s somewhere after the most significant digit, but the
representations in bases 4, 5, 6, 7, 8, 9 do not. Since there are 6 such representations, the fullness quotient of 94 is 6.
Write a method named fullnessQuotient that returns the fullness quotient of its argument. If the
argument is less than 1 return -1. Its signature is
int fullnessQuotient(int n)
Hint: use modulo and integer arithmetic to convert n to its various representations Examples:

if n is return Because
Because all of its representations do not have a 0 anywhere after the most significant
1 8 digit:
2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9
Because 5 of the representations (4, 5, 6, 7, 8) do not have a 0 anywhere after the most
9 5 significant digit:
2: 1001, 3: 100, 4: 21, 5: 14, 6: 13, 7: 12, 8: 11, 9: 10
All its representations have a 0 somewhere after the most significant digit:
360 0 2: 101101000, 3: 111100, 4: 11220, 5: 2420, 6: 1400,
7: 1023,8: 550, 9: 440

-4 -1 The argument must be > 0


public class FullnessQuotient {

public static void main(String[] args) {


System.out.println(fullnessQuotient(94));
System.out.println(fullnessQuotient(1));
System.out.println(fullnessQuotient(9));
System.out.println(fullnessQuotient(360));
System.out.println(fullnessQuotient(-4));
}

static int fullnessQuotient1(int n) {


if (n < 1)
return -1;

int count = 0;

for (int base = 2; base <= 9; base++) {


boolean zeroFlag = false;
for (int num = n; num > 0; num /= base) {
if (num % base == 0) {
zeroFlag = true;
break;
}
}
if (!zeroFlag)
count++;
}
return count;
}

static int fullnessQuotient(int n) {


if (n < 1)
return -1;

int count = 0;
for (int base = 2; base <= 9; base++) {
boolean zeroFlag = false;
int number = n;
while (number > 0) {
if (number % base == 0) {
zeroFlag = true;
break;
}
number /= base;
}

if (!zeroFlag)
count++;
}
return count;
}
}
2. Define an array to be packed if all its values are positive, each value n appears n times
and all equal values are in consecutive locations. So for example, {2, 2, 3, 3, 3} is
packed because 2 appears twice and 3 appears three times. But {2, 3, 2, 3, 3} is not
packed because the 2s are not in consecutive locations. And {2, 2, 2, 3, 3, 3} is not
packed because 2 appears three times.
Write a method named isPacked that returns 1 if its array argument is packed, otherwiseit
returns 0. You may assume that the array is not null

If you are programming in Java or C#, the function signatureis int isPacked(int[ ] a)
If you are programming in C++ or C, the function signature is int isPacked(int a[ ], int len) where len
is the length of thearray. Examples

function
a is returns reason
because there are two 2s and one 1 and equal values appear in consecutive
{2, 2, 1} 1 locations.
{2, 2, 1,2, 2} 0 Because there are groups of four 2) 2s (doesn't matter that they are in

{4, 4, 4, 4, 1, 2, 2, 3, because 4 occurs four times, 3 appears three times, 2 appears two times
3, 3} 1 and 1 appears once and equal values are in consecutive locations.

{7, 7, 7, 7, 7, 7, 7, 1} 1 Because 7 occurs seven times and 1 occurs once.


because the 7s are not in consecutive locations.
{7, 7, 7, 7, 1, 7, 7, 7} 0
1 because 7 occurs seven times
{7, 7, 7,7, 7, 7, 7}
{} 1 because there is no value that appears the wrong number of times

{1, 2, 1} 0 because there are too many 1s


{2, 1, 1} 0 because there are too many 1s
{-3, -3,-3} 0 because not all values are positive

{0, 2, 2} 0 because 0 occurs one time, not zero times.

{2, 1, 2} 0 because the 2s are not in consecutive locations

Hint: Make sure that your solution handles all the above examples correctly!

public class PackedArray {

public static void main(String[] args) {


System.out.println(isPacked(new int[]{2, 2, 3, 3, 3}));
System.out.println(isPacked(new int[]{2, 2, 2, 3, 3, 3}));
System.out.println(isPacked(new int[]{2, 2, 1}));
System.out.println(isPacked(new int[]{2, 2, 1, 2, 2}));
System.out.println(isPacked(new int[]{4, 4, 4, 4, 1, 2, 2, 3, 3, 3}));
System.out.println(isPacked(new int[]{7, 7, 7, 7, 7, 7, 7,
1}));
System.out.println(isPacked(new int[]{7, 7, 7, 7, 1, 7, 7, 7}));
System.out.println(isPacked(new int[]{7, 7, 7, 7, 7, 7, 7}));
System.out.println(isPacked(new int[]{}));
System.out.println(isPacked(new int[]{1, 2, 1}));
System.out.println(isPacked(new int[]{2, 1, 1}));
System.out.println(isPacked(new int[]{-3, -3, -3}));
System.out.println(isPacked(new int[]{0, 2, 2}));
System.out.println(isPacked(new int[]{2, 1, 2}));
}

static int isPacked(int[] a) {


int j = 0;
for (int i = 0; i < a.length; i = j) {
int count = 0;
if (a[i] <= 0)
return 0;
for (j = i; j < i + a[i]; j++) {
if (a[i] != a[j]) {
return 0;
}
}

for (int anA : a) {


if (anA == a[i])
count++;
}
if (count > a[i])
return 0;
}

return 1;
}
}

3. An array is defined to be odd-heavy if it contains at least one odd element and every
element whose value is odd is greater than every even-valued element. So {11, 4, 9, 2,
8} is odd-heavy because the two odd elements (11 and 9) are greater than all the even
elements. And {11, 4, 9, 2, 3, 10} is not odd-heavy because the even element 10 is
greater than the odd element 9.
Write a function called isOddHeavy that accepts an integer array and returns 1 if
the array is odd-heavy; otherwise it returns 0.
If you are programming in Java or C#, the function signature is int isOddHeavy(int[ ] a)
If you are programming in C or C++, the function signature is int isOddHeavy(int a[ ],
int len) where len is the number of elements in the array Some other examples:
if the input isOddHeavy reason
array is return
{1} 1 (true vacuously)

{2} 0 (contains no odd elements)

{1, 1, 1, 1,1, 1} 1
{2, 4, 6, 8, 11} 1
(11, the only odd-valued element is greater than all even-valued
elements.
{-2, -4, -6,-8, - 0 0 (-8, an even-valued element is greater than -11 an odd-valued
11} element.)
public class OddHeavy {

public static void main(String[] args) {


System.out.println(isOddHeavy(new int[]{11, 4, 9, 2, 8}));
System.out.println(isOddHeavy(new int[]{11, 4, 9, 2, 3, 10}));
System.out.println(isOddHeavy(new int[]{1}));
System.out.println(isOddHeavy(new int[]{2}));
System.out.println(isOddHeavy(new int[]{1, 1, 1, 1, 1, 1}));
System.out.println(isOddHeavy(new int[]{2, 4, 6, 8, 11}));
System.out.println(isOddHeavy(new int[]{-2, -4, -6, -8, -
11}));
}

static int isOddHeavy(int[] a) {


boolean oddFlag = false;
int smallestOdd = Integer.MAX_VALUE;
int largestEven = Integer.MIN_VALUE;

for (int anA : a) {


if (anA % 2 != 0) {
oddFlag = true;

if (anA < smallestOdd)


smallestOdd = anA;
} else {
if (anA > largestEven)
largestEven = anA;
}
}

if (oddFlag && smallestOdd > largestEven)


return 1;
else return 0;
}
}
This exam is two hours long and contains three questions. Please
indent your code so it is easy for the grader to read it.

1. Write a method named getExponent(n, p) that returns the largest exponent x such
that px evenly divides n. If p is <= 1 the method should return -1.
For example, getExponent(162, 3) returns 4 because 162 = 21 * 34, therefore the value
of x here is 4.
The method signature is int getExponent(int n, int p) Examples:

n is P is return Because

27 3 3 33 divides 27 evenly but 34 does


not.
28 3 0 30 divides 28 evenly but 31 does
not.
71 divides 280 evenly but 72 does
280 7 1
not.
53 divides -250 evenly but 54 does
-250 5 3
not.
18 1 -1 if p <=1 the function returns -1.
43 divides 128 evenly but 44 does
128 4 3
not.

public class Exponent {

public static void main(String[] args) {


System.out.println(getExponent(162, 3));
System.out.println(getExponent(27, 3));
System.out.println(getExponent(28, 3));
System.out.println(getExponent(280, 7));
System.out.println(getExponent(-250, 5));
System.out.println(getExponent(18, 1));
System.out.println(getExponent(128, 4));
}

static int getExponent1(int n, int p) {


if (p <= 1)
return -1;
int count = 0;
n = n > 0 ? n : -n;
for (int num = n; num > 0; num /= p) {
if (num % p == 0)
count++;
else break;
}
return count;
}
static int getExponent(int n, int p) {
if (p <= 1)
return -1;

int count = 0;
n = n > 0 ? n : -n;

while (n > 0) {
if (n % p == 0)
count++;
else break;

n /= p;
}
return count;
}
}

2. A binary representation of a number can be used to select elements from an array. For
example,

n: 88 = 23 + 24 + 26 (1011000)

array 8 4 9 0 3 1 2
indexes 0 1 2 3 4 5 6
result 0 3 2

so the result of filtering {8, 4, 9, 0, 3, 1, 2} using 88 would be {0, 3, 2}

In the above, the elements that are selected are those whose indices are used as exponents in the
binary representation of 88. In other words, a[3], a[4], and a[6] are selected for the result because
3, 4 and 6 are the powers of 2 that sum to 88.

Write a method named filterArray that takes an array and a non-negative integer and returns the
result of filtering the array using the binary representation of the integer. The returned array must
big enough to contain the filtered elements and no bigger. So in the above example, the returned
array has length of 3, not 7 (which is the size of the original array.)

Futhermore, if the input array is not big enough to contain all the selected elements, then
the method returns null. For example, if n=3 is used to filter the array a = {18}, the method
should return null because 3=20+21 and hence requires that the array have at least 2 elements a[0]
and a[1], but there is no a[1].

If you are using Java or C#, the signature of the function is int[ ] filterArray(int[ ] a, int n)

If you are using C or C++, the signature of the function is int * filterArray(int a[ ], int len, int n)
where len is the length of the array a
Hint: Proceed as follows Compute the size of the returned array by counting the number of 1s in
the binary representation of n (You can use modulo 2 arithmetic to determine the 1s in the binary
represention of n)

a. Allocate an array of the required size


b. Fill the allocated array with elements selected from the input array

Examples

if a is and n is return because

because there are no 1s in the binary


{9, -9} 0 {}
representation of 0
{9, -9} 1 {9} because 1 = 20 and a[0] is 9
{9, -9} 2 {-9} because 2 = 21 and a[1] is -9
{9, -9} 3 {9, -9} because 3 = 20 + 21 and a[0]=9, a[1]=-9
{9, -9} 4 null because 4 = 22 and there is no a[2]
{9, -9, 5} 3 {9, -9} because 3 = 20 + 21 and a[0]=9, a[1]=-9
because 11 = 20 + 21 + 23 and a[0]=0,
{0, 9, 12, 18, -6} 11 {0, 9, 18}
a[1]=9, a[3]=18

import java.util.Arrays;
public class BinaryRepresentation {

public static void main(String[] args) {


System.out.println(Arrays.toString(filterArray(new int[]{8, 4,
9, 0, 3, 1, 2}, 88)));
System.out.println(Arrays.toString(filterArray(new int[]{18},
3)));
System.out.println(Arrays.toString(filterArray(new int[]{9, -
9}, 0)));
System.out.println(Arrays.toString(filterArray(new int[]{9, -
9}, 1)));
System.out.println(Arrays.toString(filterArray(new int[]{9, -
9}, 2)));
System.out.println(Arrays.toString(filterArray(new int[]{9, -
9}, 3)));
System.out.println(Arrays.toString(filterArray(new int[]{9, -
9}, 4)));
System.out.println(Arrays.toString(filterArray(new int[]{9, -
9, 5}, 3)));
System.out.println(Arrays.toString(filterArray(new int[]{0, 9,
12, 18, -6}, 11)));
}

static int[] filterArray(int[] a, int n) {


int size = 0;
for (int number = n; number > 0; number /= 2) {
if (number % 2 == 1)
size++;
}
int[] result = new int[size];
int i = 0;
int index = 0;
for (int number = n; number > 0; number /= 2) {
if (number % 2 == 1){
if (index >= a.length)
return null;
result[i] = a[index];
i++;
}
index++;
}
return result;
}
}

public class FilterArray {

static int isFilter1(int[] a) {


boolean cond1 = true;
boolean cond2 = true;

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

if (a[i] == 9) {
for (int j = 0; j < a.length; j++) {
if (a[j] == 11) {
cond1 = true;
break;
} else cond1 = false;
}
}

if (a[i] == 7) {
for (int k = 0; k < a.length; k++) {
if (a[k] == 13) {
cond2 = false;
break;
} else cond2 = true;
}
}

if (cond1 && cond2) return 1;


else return 0;
}

static int isFilter(int[] a) {


boolean cond9Flag = false;
boolean cond7Flag = false;
boolean cond11Flag = false;
boolean cond13Flag = false;

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


if (a[i] == 9) {
cond9Flag = true;
} else if (a[i] == 11) {
cond11Flag = true;
} else if (a[i] == 7) {
cond7Flag = true;
} else if (a[i] == 13) {
cond13Flag = true;
}
}

if ((cond9Flag && cond11Flag) || (cond7Flag && !cond13Flag) ||


(!cond9Flag && !cond7Flag))
return 1;
return 0;
}
}

public class FilterArrayTest {

public static void main(String[] args) {


System.out.println(FilterArray.isFilter(new int[]{1, 2, 3, 9,
6, 11}));
System.out.println(FilterArray.isFilter(new int[]{3, 4, 6, 7,
14, 16}));
System.out.println(FilterArray.isFilter(new int[]{1, 2, 3, 4,
10, 11, 13}));
System.out.println(FilterArray.isFilter(new int[]{3, 6, 5, 5,
13, 6, 13}));
System.out.println(FilterArray.isFilter(new int[]{9, 6, 18}));
System.out.println(FilterArray.isFilter(new int[]{4, 7, 13}));
}
}

There are three questions on this exam. You have 2 hours to complete it.
Please indent your program so that it is easy for the grader to read.

1. Write a function named largestAdjacentSum that iterates through an array computing the sum of
adjacent elements and returning the largest such sum. You may assume that the array has at least 2
elements.
If you are writing in Java or C#, the function signature is int largestAdjacentSum(int[ ] a)
If you are writing in C or C++, the function signature is int largestAdjacentSum(int a[ ], int len)
where len is the number of elements in a Examples:

if a is return reason
{1, 2, 3, 4} 7 because 3+4 is larger than either 1+2 or 2+3
{18, -12, 9, -10} 6 because 18-12 is larger than -12+9 or 9-10
{1,1,1,1,1,1,1,1,1} 2 because all adjacent pairs sum to 2
{1,1,1,1,1,2,1,1,1} 3 because 1+2 or 2+1 is the max sum of adjacent pairs

public class AdjacentSum {

public static void main(String[] args) {


System.out.println(largestAdjacentSum(new int[]{1, 2, 3, 4}));
System.out.println(largestAdjacentSum(new int[]{18, -12, 9, -10}));
System.out.println(largestAdjacentSum(new int[]{1,1,1,1,1,1,1,1,1}));
System.out.println(largestAdjacentSum(new int[]{1,1,1,1,1,2,1,1,1}));
}

static int largestAdjacentSum(int[] a) {


int sum = 0;

for (int i = 0; i < a.length - 1; i++) {


if (a[i] + a[i + 1] > sum) {
sum = a[i] + a[i + 1];
}
}
return sum;
}
}

2. The number 198 has the property that 198 = 11 + 99 + 88, i.e., if each of its digits is concatenated
twice and then summed, the result will be the original number. It turns out that 198 is the only number
with this property. However, the property can be generalized so that each digit is concatenated n
times and then summed. For example, 2997 = 222+999+999+777 and here each digit is concatenated
three times. Write a function named checkContenatedSum that tests if a number has this generalized
property.

The signature of the function is int checkConcatenatedSum(int n, int catlen) where n is the number
and catlen is the number of times to concatenate each digit before summing. The function returns 1 if
n is equal to the sum of each of its digits contenated catlen times. Otherwise, it returns 0. You may
assume that n and catlen are greater than zero
Hint: Use integer and modulo 10 arithmetic to sequence through the digits of the argument.
Examples:

if n is and catlen is return reason


198 2 1 because 198 == 11 + 99 + 88
198 3 0 because 198 != 111 + 999 + 888
2997 3 1 because 2997 == 222 + 999 + 999 + 777
2997 2 0 because 2997 != 22 + 99 + 99 + 77
13332 4 1 because 13332 = 1111 + 3333 + 3333 + 3333 + 2222
9 1 1 because 9 == 9

public class ConcatenatedSum {

public static void main(String[] args) {


System.out.println(checkConcatenatedSum(198, 2));
System.out.println(checkConcatenatedSum(198, 3));
System.out.println(checkConcatenatedSum(2997, 3));
System.out.println(checkConcatenatedSum(2997, 2));
System.out.println(checkConcatenatedSum(13332, 4));
System.out.println(checkConcatenatedSum(9, 1));
}

static int checkConcatenatedSum(int n, int catlen) {


int tempNum = n;
int sum = 0;

while (tempNum > 0) {


int digit = tempNum % 10;
tempNum /= 10;
for (int i = 1, j = 1; j <= catlen; i *= 10, j++) {
sum += digit * i;
}
}
if (n == sum) return 1;
return 0;
}
}

3. Define an m-n sequenced array to be an array that contains one or more occurrences of all the
integers between m and n inclusive. Furthermore, the array must be in ascending order and
contain only those integers. For example, {2, 2, 3, 4, 4, 4, 5} is a 2-5 sequenced array. The
array {2, 2, 3, 5, 5, 5} is not a 2-5 sequenced array because it is missing a 4. The array {0, 2,
2, 3, 3} is not a 2-3 sequenced array because the 0 is out of range. And {1,1, 3, 2, 2, 4} is not
a 1-4 sequenced array because it is not in ascending order.

Write a method named isSequencedArray that returns 1 if its argument is a m-n sequenced
array, otherwise it returns 0.
If you are writing in Java or C# the function signature is int isSequencedArray(int[ ] a, int m,
int n)

If you are writing in C or C++ the function signature is int isSequencedArray(int a[ ], int len,
int m, int n) where len is the number of elements in the array a. You may assume that m<=n
Examples
if a is and m is and n return reason
is
because the array contains all the numbers between 1
{1, 2, 3, 4, 5} 1 5 1
and 5 inclusive in ascending order and no other
numbers.
{1, 3, 4, 2, 5} 1 5 0 because the array is not in ascending order.
{-5, -5, -4, -4, -4, -3, -3, -2, -5 -2 1 because the array contains all the numbers between -5 and -
-2, -2} 2 inclusive in ascending order and no other numbers. Note
that duplicates are allowed.
{0, 1, 2, 3, 4, 5} 1 5 0 because 0 is not in between 1 and 5 inclusive
{1, 2, 3, 4} 1 5 0 because there is no 5
{1, 2, 5} 1 5 0 because there is no 3 or 4
because the array does not start with a 1.
{5, 4, 3, 2, 1} 1 5 0
Furthermore, it is not in ascending order.

public class SequencedArray {

public static void main(String[] args) {


System.out.println(isSequencedArray(new int[]{2, 2, 3, 4, 4, 4, 5}, 2, 5));
System.out.println(isSequencedArray(new int[]{2, 2, 3, 5, 5, 5}, 2, 5));
System.out.println(isSequencedArray(new int[]{0, 2, 2, 3, 3}, 2, 3));
System.out.println(isSequencedArray(new int[]{1, 1, 3, 2, 2, 4}, 1, 4));
System.out.println(isSequencedArray(new int[]{1, 2, 3, 4, 5}, 1, 5));
System.out.println(isSequencedArray(new int[]{1, 3, 4, 2, 5}, 1, 5));
System.out.println(isSequencedArray(new int[]
{-5, -5, -4, -4, -4, -3, -3, -2, -2, -2}, -5, -2));
System.out.println(isSequencedArray(new int[]{0, 1, 2, 3, 4, 5}, 1, 5));
System.out.println(isSequencedArray(new int[]{1, 2, 3, 4}, 1, 5));
System.out.println(isSequencedArray(new int[]{1, 2, 5}, 1, 5));
System.out.println(isSequencedArray(new int[]{5, 4, 3, 2, 1}, 1, 5));
}

static int isSequencedArray(int[] a, int m, int n) {


if (a.length <= 1 || a[0] != m|| a[a.length - 1] !=n || m > n)
return 0;
for (int i = m; i <= n; i++) {
boolean flag = false;
for (int j = 1; j <= a.length - 1; j++) {
if (a[j - 1] > a[j]) {
return 0;
}
if (a[j - 1] == i || a[j] == i) {
flag = true;
break;
}
}
if (!flag)
return 0;
}
return 1;
}
}
There are three questions on this exam. You have 2 hours to complete it. Please
indent your programs so that it is easy for the grader to read.

1. Write a function named largestPrimeFactor that will return the largest prime
factor of a number. If the number is <=1 it should return 0. Recall that a prime
number is a number > 1 that is divisible only by 1 and itself, e.g., 13 is prime but
14 is not.

The signature of the function is int largestPrimeFactor(int n)

Examples:

if n is return because
10 5 because the prime factors of 10 are 2 and 5 and 5 is the largest one.
6936 17 because the distinct prime factors of 6936 are 2, 3 and 17 and 17 is the largest
1 0 because n must be greater than 1

import java.util.Arrays;
public class PrimeFactor {

public static void main(String[] args) {


System.out.println(largestPrimeFactor(10));
System.out.println(largestPrimeFactor(6936));
System.out.println(largestPrimeFactor(1));
System.out.println(largestPrimeFactor(11));
}

static int largestPrimeFactor(int n) {


if (n <= 1)
return 0;
int largestPrimeFactor = 2;

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


if (n % i == 0 && isPrime(i)) {
largestPrimeFactor = i;
}
}
return largestPrimeFactor;
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}

return n > 0;
}
2. The fundamental theorem of arithmetic states that every natural number greater than
1 can be written as a unique product of prime numbers. So, for instance,
6936=2*2*2*3*17*17. Write a method named encodeNumber what will encode a
number n as an array that contains the prime numbers that, when multipled together,
will equal n. So encodeNumber(6936) would return the array {2, 2, 2, 3, 17, 17}. If
the number is <= 1 the function should return null;

If you are programming in Java or C#, the function signature is int[ ] encodeNumber(int n)
If you are programming in C or C++, the function signature is int *encodeNumber(int n) and the
last element of the returned array is 0.

Note that if you are programming in Java or C#, the returned array should be big
enough to contain the prime factors and no bigger. If you are programming in C or
C++ you will need one additional element to contain the terminating zero.
Hint: proceed as follows:

1. Compute the total number of prime factors including duplicates.


2. Allocate an array to hold the prime factors. Do not hard-code the size of the returned
array!!
3. Populate the allocated array with the prime factors. The elements of the array when
multiplied together should equal the number. Examples

if n is return reason
2 {2} because 2 is prime
6 {2, 3} because 6 = 2*3 and 2 and 3 are prime.
14 {2, 7} because 14=2*7 and 2 and 7 are prime numbers.
24 {2, 2, 2, 3} because 24 = 2*2*2*3 and 2 and 3 are prime
1200 {2, 2, 2, 2, 3, 5, 5} because 1200=2*2*2*2*3*5*5 and those are all prime
1 null because n must be greater than 1
-18 null because n must be greater than 1

import java.util.Arrays;
public class EncodeNumber {

public static void main(String[] args) {


System.out.println(Arrays.toString(encodeNumber(6936)));
System.out.println(Arrays.toString(encodeNumber(2)));
System.out.println(Arrays.toString(encodeNumber(6)));
System.out.println(Arrays.toString(encodeNumber(14)));
System.out.println(Arrays.toString(encodeNumber(24)));
System.out.println(Arrays.toString(encodeNumber(1200)));
System.out.println(Arrays.toString(encodeNumber(1)));
System.out.println(Arrays.toString(encodeNumber(-18)));
}
static int[] encodeNumber(int n) {
if (n <= 1)
return null;

int size = 0;
int nCopy = n;
for (int i = 2; i <= nCopy; ) {
if (isPrime(i) && nCopy % i == 0) {
size++;
nCopy /= i;
} else i++;
}

int[] result = new int[size];


nCopy = n;

for (int i = 0, j = 2; i < size && j <= nCopy; ) {


if (isPrime(j) && nCopy % j == 0) {
result[i] = j;
i++;
nCopy /= j;
} else j++;
}

return result;
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}

return n > 0;
}
}

3. Consider a simple pattern matching language that matches arrays of integers. A pattern is an
array of integers. An array matches a pattern if it contains sequences of the pattern elements in
the same order as they appear in the pattern. So for example, the array {1, 1, 1, 2, 2, 1, 1, 3}
matches the pattern {1, 2, 1, 3} as follows:

{1, 1, 1, 2, 2, 1, 1, 3} {1, 2, 1, 3} (first 1 of pattern matches three 1s in array)


{1, 1, 1, 2, 2, 1, 1, 3} {1, 2, 1, 3} (next element of pattern matches two 2s in array)
{1, 1, 1, 2, 2, 1, 1, 3} {1, 2, 1, 3} (next element of pattern matches two 1s in array)
{1, 1, 1, 2, 2, 1, 1, 3} {1, 2, 1, 3} (last element of pattern matches one 3 in array)

The pattern must be completely matched, i.e. the last element of the array must be matched by the last
element of the pattern. Here is an incomplete function that does this pattern matching. It returns 1 if
the pattern matches the array, otherwise it returns 0.

static int matchPattern(int[] a, int len, int[] pattern, int patternLen) {


// len is the number of elements in the array a, patternLen is the number of elements in the pattern.
int i=0; // index into a
int k=0; // index into pattern
int matches = 0; // how many times current
pattern character has been matched so far for
(i=0; i <len; i++) {
if (a[i] == pattern[k])
matches++; // current pattern character was matched
else if (matches == 0 || k == patternLen-1)
return 0; // if pattern[k] was never matched
(matches==0) or at end of pattern (k==patternLen-1) else //
advance to next pattern character {
!!You write this code!!
} // end of else
} // end of for

// return 1 if at end of array a (i==len) and


also at end of pattern (k==patternLen-1) if
(i==len && k==patternLen-1) return 1; else
return 0;
}
Please finish this function by writing the code for the last else statement. Your answer
just has to include this code, you do not have to write the entire function.

Hint: You need at least 4 statements (one of them an if statement) Examples

if a is and pattern is return reason


{1, 1, 1, 1, 1} {1} 1 because all elements of the array match the pattern element 1
{1} {1} 1 because all elements of the array match the pattern element 1
because the first two 1s of the array are matched by the first pattern
{1, 1, 2, 2, 2, 2} {1, 2} 1
element, last four 2s of array are matched by the last pattern element
{1, 2, 3} {1, 2} 0 because the 3 in the array is not in the pattern.
{1, 2} {1, 2, 3} 0 because the 3 in the pattern is not in the array
{1, 1, 2, 2, 2, 2, 3} {1, 3} 0 because at least one 3 must appear after the sequence of 1s.
{1, 1, 1, 1} {1, 2} 0 because the array ends without matching the pattern element 2.
{1, 1, 1, 1, 2, 2, 3, 3} {1, 2} 0 because the element 3 of the array is not matched
because the 10 element is not matched by the 4 pattern element. Be
{1, 1, 10, 4, 4, 3} {1, 4, 3} 0
sure your code handles this situation correctly!
public class PatternMatcher {

public static void main(String[] args) {


System.out.println(matchPattern(new int[]{1, 1, 1, 2, 2, 1, 1,
3}, new int[]{1, 2, 1, 3}));
System.out.println(matchPattern(new int[]{1, 1, 1, 1, 1}, new
int[]{1}));
System.out.println(matchPattern(new int[]{1}, new int[]{1}));
System.out.println(matchPattern(new int[]{1, 1, 2, 2, 2, 2},
new int[]{1, 2}));
System.out.println(matchPattern(new int[]{1, 2, 3}, new
int[]{1, 2}));
System.out.println(matchPattern(new int[]{1, 2}, new int[]{1,
2, 3}));
System.out.println(matchPattern(new int[]{1, 1, 2, 2, 2, 2,
3}, new int[]{1, 3}));
System.out.println(matchPattern(new int[]{1, 1, 1, 1}, new
int[]{1, 2}));
System.out.println(matchPattern(new int[]{1, 1, 1, 1, 2, 2, 3,
3}, new int[]{1, 2}));
System.out.println(matchPattern(new int[]{1, 1, 10, 4, 4, 3},
new int[]{1, 4, 3}));
}

static int matchPattern(int[] a, int[] pattern) {


int i = 0;
int k = 0;
int matches = 0;

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


if (a[i] == pattern[k])
matches++;

else if (matches == 0 || k == pattern.length - 1)


return 0;

else {
k++;
if (a[i] == pattern[k])
matches++;
else return 0;
}
}

if (i == a.length && k == pattern.length - 1)


return 1;
else return 0;
}
}
There are three questions on this exam. You have 2 hours to
complete it. Please indent your program so that it is easy for
the grader to read.
1. Define the n-based integer rounding of an integer k to be the nearest multiple of n to
k. If two multiples of n are equidistant use the greater one. For example the 4-based
rounding of 5 is 4 because 5 is closer to 4 than it is to 8, the 5-based rounding of 5 is 5
because 5 is closer to 5 that it is to 10, the 4-based rounding of 6 is 8 because 6 is
equidistant from 4 and 8, so the greater one is used, the 13-based rounding of 9 is 13,
because 9 is closer to 13 than it is to 0,

Write a function named oIntegerBasedRounding that takes an integer array and


rounds all its positive elements using n-based integer rounding.

A negative element of the array is not modified and if n <=0, no elements of the array are
modified. Finally you may assume that the array has at least two elements.

Hint: In integer arithmetic, (6/4) * 4 = 4

If you are programming in Java or C#, the function signature is void doIntegerBasedRounding(int[ ] a,
int n) where n is used to do the rounding

If you are programming in C or C++, the function signature is void doIntegerBasedRounding(int a[ ],


int n, int len) where n is used to do the rounding and len is the number of elements in the array a.
Examples

if a is and n is then a becomes reason


because the 2-based rounding of 1 is 2, the 2-based
{1, 2, 3, 4, 5} 2 {2, 2, 4, 4, 6} rounding of 2 is 2, the 2-based rounding of 3 is 4, the 2-
based rounding of 4 is 4, and the 2-based rounding
of 5 is 6.
because the 3-based rounding of 1 is 0, the 3-based
{1, 2, 3, 4, 5} 3 {0, 3, 3, 3, 6} roundings of 2, 3, 4 are all 3, and the 3-based
rounding of 5 is 6.
{1, 2, 3, 4, 5} -3 {1, 2, 3, 4, 5} because the array is not changed if n <= 0.
{-1, -2, -3, -4, -5} 3 {-1, -2, -3, -4, -5} because negative numbers are not rounded
because -18 is negative and hence is not modified, the 4-
{-18, 1, 2, 3, 4, 5} 4 {-18, 0, 4, 4, 4, 4} based rounding of 1 is 0, and the 4-based
roundings of 2, 3, 4, 5 are all 4.
{1, 2, 3, 4, 5} 5 {0, 0, 5, 5, 5}
{1, 2, 3, 4, 5} 100 {0, 0, 0, 0, 0}

import java.util.Arrays;

public class IntegerBasedRounding {

public static void main(String[] args) {


int[] a = new int[]{1, 2, 3, 4, 5};
doIntegerBasedRounding(a, 2);
System.out.println(Arrays.toString(a));

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


doIntegerBasedRounding(b, 3);
System.out.println(Arrays.toString(b));

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


doIntegerBasedRounding(c, -3);
System.out.println(Arrays.toString(c));

int[] d = new int[]{-1, -2, -3, -4, -5};


doIntegerBasedRounding(d, 3);
System.out.println(Arrays.toString(d));

int[] e = new int[]{-18, 1, 2, 3, 4, 5};


doIntegerBasedRounding(e, 4);
System.out.println(Arrays.toString(e));

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


doIntegerBasedRounding(f, 5);
System.out.println(Arrays.toString(f));

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


doIntegerBasedRounding(g, 100);
System.out.println(Arrays.toString(g));
}

static void doIntegerBasedRounding(int[] a, int n) {


if (n > 0) {
for (int i = 0; i < a.length; i++) {
int j = 1;
if (a[i] < 0)
continue;
while (true) {
int prev = n * (j - 1);
int next = n * j;

if (a[i] >= prev && a[i] <= next) {


if (a[i] == prev)
a[i] = prev;
else if (a[i] == next)
a[i] = next;
else if (a[i] - prev == next - a[i])
a[i] = next;
else if (a[i] - prev > next - a[i])
a[i] = next;
else a[i] = prev;

break;
}
j++;
}
}
}
}
}

2. A number n>0 is called cube-powerful if it is equal to the sum of the cubes of its digits.
Write a function named isCubePowerful that returns 1 if its argument is cube-powerful; otherwise it
returns 0.
The function prototype is int isCubePowerful(int n);
Hint: use modulo 10 arithmetic to get the digits of the number. Examples:

if n is return because

153 1 because 153 = 13 + 53 + 33


370 1 because 370 = 33 + 73 + 03
371 1 because 371 = 33 + 73 + 13
407 1 because 407 = 43 + 03 + 73
87 0 because 87 != 83 + 73
because n must be greater than 0.
0 0
because n must be greater than 0.
-81 0

public class CubePowerful {

public static void main(String[] args) {


System.out.println(isCubePowerful(153));
System.out.println(isCubePowerful(370));
System.out.println(isCubePowerful(371));
System.out.println(isCubePowerful(407));
System.out.println(isCubePowerful(87));
System.out.println(isCubePowerful(0));
System.out.println(isCubePowerful(-81));
}

static int isCubePowerful(int n) {


if (n<=0)
return 0;

int nCopy = n;
int sum = 0;
while (nCopy > 0) {
int digit = nCopy % 10;
nCopy /= 10;
int product = 1;

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


product *= digit;
}
sum += product;
}

if (sum == n)
return 1;
return 0;
}
}

3. A number can be encoded as an integer array as follows. The first element of the array is any number
and if it is negative then the encoded number is negative. Each digit of the number is the absolute
value of the difference of two adjacent elements of the array. The most significant digit of the number
is the absolute value of the difference of the first two elements of the array. For example, the array {2,
-3, -2, 6, 9, 18} encodes the number 51839 because

a. 5 is abs(2 - (-3))
b. 1 is abs(-3 - (-2))
c. 8 is abs(-2 - 6)
d. 3 is abs(6-9)
e. 9 is abs(9-18)

The number is positive because the first element of the array is >= 0.

If you are programming in Java or C#, the function prototype is int decodeArray(int[ ] a)

If you are programming in C or C++, the function prototype is


int decodeArray(int a[ ], int len) where len is the length of array a;

You may assume that the encoded array is correct, i.e., the absolute value of the
difference of any two adjacent elements is between 0 and 9 inclusive and the array has
at least two elements.

Examples

a is Function returns reason


{0, -3, 0, -4, 0} 3344 because abs(0-(-3)=3, abs(-3-0)=3, abs(0-(-4))=4, abs(-4-0)=4
because abs(-1-5)=6, abs(5-8)=3, abs(8-17)=9, abs(17-15)=2;
{-1, 5, 8, 17, 15} -6392 the number is negative because the first element of the array
is negative
because abs(1-5)=4, remaining digits are the same as previous
{1, 5, 8, 17, 15} 4392 example; the number is positive because the first element of
the array is >=0.
because abs(111-115)=4, abs(115-118)=3, abs(118-127)=9,
{111, 115, 118, 127, 125} 4392 abs(127-125)=2; the number is positive because the first
element of the array is >=0.
{1, 1} 0 because abs(1-1) = 0
public class DecodeArray {

public static void main(String[] args) {


System.out.println(decodeArray(new int[]{2, -3, -2, 6, 9, 18}));
System.out.println(decodeArray(new int[]{0, -3, 0, -4, 0}));
System.out.println(decodeArray(new int[]{-1, 5, 8, 17, 15}));
System.out.println(decodeArray(new int[]{1, 5, 8, 17, 15}));
System.out.println(decodeArray(new int[]{111, 115, 118, 127, 125}));
System.out.println(decodeArray(new int[]{1, 1}));

System.out.println("\n\n" + decodeArray2(new int[]{1}));


System.out.println(decodeArray2(new int[]{0, 1}));
System.out.println(decodeArray2(new int[]{-1, 0, 1}));
System.out.println(decodeArray2(new int[]{0, 1, 1, 1, 1, 1, 0, 1}));
System.out.println(decodeArray2(new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}));
System.out.println(decodeArray2(new int[]{0, 1, 0, 0, 1, 0, 0, 0, 1,
0, 0, 0, 0, 1}));
System.out.println(decodeArray2(new int[]{-1, 0, 0, 1, 1, 0, 1}));
}

static int decodeArray(int[] a) {


int sum = 0;

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


int digit = (a[i] - a[i - 1]) > 0 ? (a[i] - a[i - 1]):
- (a[i] - a[i - 1]);

for (int j = i; j < a.length - 1; j++) {


digit *= 10;
}
sum += digit;
}

if (a[0] < 0) return -sum;


return sum;
}

static int decodeArray2(int[] a) {


int sum = 0;

int position = 0;
for (int i = a.length - 1; i > 0; i--) {
int digit = 0;

for (int j = i; j > 0; j--) {


if (a[j - 1] != 0) {
i = j;
break;
}
digit++;
i = j;
}

for (int j = 0; j < position; j++) {


digit *= 10;
}
sum += digit;

position++;
}

if (a[0] < 0) return -sum;


return sum;
}
}

There are three questions on this exam. You have 2 hours to complete it.
1. An array is zero-plentiful if it contains at least one 0 and every sequence of 0s is of length at least 4.
Write a method named isZeroPlentiful which returns the number of zero sequences if its array
argument is zero-plentiful, otherwise it returns 0.

If you are programming in Java or C#, the function signature is int isZeroPlentiful(int[ ] a)
If you are programming in C or C++, the function signature is
int isZeroPlentiful(int a[ ], int len) where len is the number of elements in the array a. Examples

a is Function returns reason

{0, 0, 0, 0, 0}1 1 because there is one sequence of 0s and its length >= 4.
{1, 2, 0, 0, 0, 0, 2, -18, 0, 0, 0, 0, 0, 2 because there are two sequences of 0s and both have
12}1 lengths
>= 4.
{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 8, 0, 0, 0, 0, 3 because three are three sequences of zeros and all have
0, 0}1 length
>=4
{1, 2, 3, 4}1 0 because there must be at least one 0.
{1, 0, 0, 0, 2, 0, 0, 0, 0} 0 because there is a sequence of zeros whose length is less
< 4.
{0} 0 because there is a sequence of zeroes whose length is <
4.
{} 0 because there must be at least one 0.

public class ZeroPlentiful {

public static void main(String[] args) {


System.out.println(isZeroPlentiful(new int[]{0, 0, 0, 0, 0}));
System.out.println(isZeroPlentiful(new int[]{
1, 2, 0, 0, 0, 0, 2, -18, 0, 0, 0, 0, 0, 12}));
System.out.println(isZeroPlentiful(new int[]{
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0}));
System.out.println(isZeroPlentiful(new int[]{1, 2, 3, 4}));
System.out.println(isZeroPlentiful(new int[]{
1, 0, 0, 0, 2, 0, 0, 0, 0}));
System.out.println(isZeroPlentiful(new int[]{0}));
System.out.println(isZeroPlentiful(new int[]{}));
}

static int isZeroPlentiful(int[] a) {


if (a.length < 4)
return 0;

int count = 0;

for (int i = 0; i < a.length - 1; ) {


if (a[i] == 0 && i + 3 <= a.length) {
int j = i;
int zeroCount = 0;

while (j < a.length && a[j] == 0) {


zeroCount++;
j++;
}

if (zeroCount < 4) {
return 0;
} else {
count++;
}

i = j;
} else i++;
}

return count;
}
}

2. A number is called digit-increasing if it is equal to n + nn + nnn + ... for some digit n between 1 and
9. For example 24 is digit- increasing because it equals 2 + 22 (here n = 2)

Write a function called isDigitIncreasing that returns 1 if its argument is digit-increasing


otherwise, it returns 0.

The signature of the method is int isDigitIncreasing(int n)


Examples
then function
if n is reason
returns
7 1 because 7 = 7 (here n is 7)
36 1 because 36 = 3 + 33
984 1 because 984 = 8 + 88 + 888
because 7404 = 6 + 66 + 666 +
7404 1
6666
public class DigitIncreasing {

public static void main(String[] args) {


System.out.println(isDigitIncreasing(24));
System.out.println(isDigitIncreasing(7));
System.out.println(isDigitIncreasing(36));
System.out.println(isDigitIncreasing(984));
System.out.println(isDigitIncreasing(7404));
}

static int isDigitIncreasing(int n) {

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


int sum = 0;
int product = 0;

while (sum < n) {


product = (product * 10) + i;
sum += product;
}

if (sum == n)
return 1;
}

return 0;
}
}

3. An integer number can be encoded as an array as follows. Each digit n of the number is represented by
n zeros followed by a 1. So the digit 5 is represented by 0, 0, 0, 0, 0, 1. The encodings of each digit of a
number are combined to form the encoding of the number. So the number 1234 is encoded as the array
{0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1}. The first 0, 1 is contributed by the digit 1, the next 0, 0, 1 is
contributed by the digit 2, and so on.

There is one other encoding rule: if the number is negative, the first element of the
encoded array must be -1, so -201 is encoded as {- 1, 0, 0, 1, 1, 0, 1}. Note that the 0
digit is represented by no zeros, i.e. there are two consecutive ones!

Write a method named decodeArray that takes an encoded array and decodes it to return the
number.

You may assume that the input array is a legal encoded array, i.e., that -1 will only appear as the
first element, all elements are either 0, 1 or -1 and that the last element is 1.

If you are programming in Java or C#, the function prototype is int decodeArray(int[ ] a)

If you are programming in C or C++, the function prototype is int decodeArray(int a[ ], int len);

Examples

then
a is function reason
returns
{1} 0 because the digit 0 is represented by no zeros
followed by
a one.
{0, 1} 1 because the digit 1 is represented by one zero
followed by
a one.
because the encoding of a negative number
{-1, 0, 1} -1 begins with a
-1 followed by the encoding of the absolute
value of the number.
because the encoding of the first 1 is 0, 1, the
{0, 1, 1, 1, 1, 1, 0, 1} 100001 encoding of each of the four 0s is just a 1 and
the encoding of the last
1 is 0, 1.
{0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1} 999 because each 9 digit is encoded as
0,0,0,0,0,0,0,0,0,1.
public class DecodeArray {

public static void main(String[] args) {


System.out.println("\n\n" + decodeArray2(new int[]{1}));
System.out.println(decodeArray2(new int[]{0, 1}));
System.out.println(decodeArray2(new int[]{-1, 0, 1}));
System.out.println(decodeArray2(new int[]{0, 1, 1, 1, 1, 1, 0,
1}));
System.out.println(decodeArray2(new int[]{0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1}));
System.out.println(decodeArray2(new int[]{0, 1, 0, 0, 1, 0, 0,
0, 1, 0, 0, 0, 0, 1}));
System.out.println(decodeArray2(new int[]{-1, 0, 0, 1, 1, 0,
1}));
}

static int decodeArray2(int[] a) {


int sum = 0;
int position = 0;
for (int i = a.length - 1; i > 0; i--) {
int digit = 0;

for (int j = i; j > 0; j--) {


if (a[j - 1] != 0) {
i = j;
break;
}
digit++;
i = j;
}

for (int j = 0; j < position; j++) {


digit *= 10;
}
sum += digit;

position++;
}

if (a[0] < 0) return -sum;


return sum;
}
}

This exam consists of three questions. You have two hours in


which to complete it.
1. An onion array is an array that satisfies the following condition for all values of j and k:
if j>=0 and k>=0 and j+k=length of array and j!=k then a[j]+a[k] <= 10
Write a function named isOnionArray that returns 1 if its array argument is an onion array and returns 0 if it is
not.
Your solution must not use a nested loop (i.e., a loop executed from inside another loop). Furthermore,
once you determine that the array is not an onion array your function must return 0; no wasted loops
cycles please!

If you are programming in Java or C#, the function signature is int isOnionArray(int[ ] a)

If you are programming in C or C++, the function signature is int isOnionArray(int a[ ], int len) where len
is the number of elements in the array a. Examples

a is function returns reason


{1, 2, 19, 4, 5} 1 because 1+5 <= 10, 2+4 <=10
{1, 2, 3, 4, 15} 0 because 1+15 > 10
{1, 3, 9, 8} 0 because 3+9 > 10
{2} 1 because there is no j, k where a[j]+a[k] > 10 and
j+k=length of array and j!=k
{} 1 because there is no j, k where a[j]+a[k] > 10 and
j+k=length of array and j!=k
{-2, 5, 0, 5, 12} 1 because -2+12 <= 10 and 5+5 <= 10

public class OnionArray {

public static void main(String[] args) {


System.out.println(isOnionArray(new int[]{1, 2, 19, 4, 5}));
System.out.println(isOnionArray(new int[]{1, 2, 3, 4, 15}));
}

static int isOnionArray(int[] a) {


if (a.length == 1 || a.length ==0)
return 1;

for (int i = 0, j = a.length - 1; i < j; i++, j--) {


if (i + j == a.length) {
if (a[i] + a[j] > 10)
return 0;
}
}
return 1;
}
}

2. A number n is called prime happy if there is at least one prime less than n and the sum of all primes less
than n is evenly divisible by n. Recall that a prime number is an integer > 1 which has only two integer
factors, 1 and itself .
The function prototype is int isPrimeHappy(int n);
Examples:

if n return because
is
5 1 because 2 and 3 are the primes less than 5, their sum is 5 and 5 evenly divides 5.
25 1 because 2, 3, 5, 7, 11, 13, 17, 19, 23 are the primes less than 25, their sum is 100 and 25
evenly divides 100
32 1 because 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 are the primes less than 32, their sum is 160
and 32 evenly divides 160
8 0 because 2, 3, 5, 7 are the primes less than 8, their sum is 17 and 8 does not evenly divide
17.
2 0 because there are no primes less than 2.
public class PrimeHappy {

public static void main(String[] args) {


System.out.println(isPrimeHappy(5));
System.out.println(isPrimeHappy(25));
System.out.println(isPrimeHappy(32));
System.out.println(isPrimeHappy(8));
System.out.println(isPrimeHappy(2));
}

static int isPrimeHappy(int n) {


int number = 2;
boolean primeFlag = false;
int sum = 0;
while (number < n) {
if (isPrime(number)) {
primeFlag = true;
sum += number;
}
number++;
}
if (primeFlag && sum % n == 0)
return 1;
else return 0;
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}

return n > 0;
}
}

3. An integer number can be encoded as an array as follows. Each digit n of the number is represented by
n zeros followed by a 1. So the digit 5 is represented by 0, 0, 0, 0, 0, 1. The encodings of each digit of a
number are combined to form the encoding of the number. So the number 1234 is encoded as the array
{0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1}. The first 0, 1 is contributed by the digit 1, the next 0, 0, 1 is
contributed by the digit 2, and so on. There is one other encoding rule: if the number is negative, the
first element of the encoded array must be -1, so -201 is encoded as {-1, 0, 0, 1, 1, 0, 1}. Note that the 0
digit is represented by no zeros, i.e. there are two consecutive ones!

Write a method named encodeArray that takes an integer as an argument and returns the encoded
array.
If you are programming in Java or C#, the function prototype is int[] encodeArray(int n)
If you are programming in C or C++, the function prototype is int * encodeArray(int n);

Hints
Use modulo 10 arithmetic to get digits of number
Make one pass through the digits of the number to compute the size of the encoded array. Make a second
pass through the digits of the number to set elements of the encoded array to 1.

Examples
n is then function returns reason
because the digit 0 is represented by no zeros
0 {1} and the representation of each digit ends in
one.
because the digit 1 is represented by one zero
1 {0, 1} and the representation of each digit ends in
one.
because the encoding of a negative number
-1 {-1, 0, 1} begins with a -1 followed by the encoding of
the absolute value of the number.
because the encoding of the first 1 is 0, 1, the
100001 {0, 1, 1, 1, 1, 1, 0, 1} encoding of each of the four 0s is just a 1 and
the encoding of the last 1 is 0, 1.
999 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, because each 9 digit is encoded as
1,0,0,0,0,0,0,0,0,0,1 0,0,0,0,0,0,0,0,0,1.

import java.util.Arrays;
public class EncodeArray {

public static void main(String[] args) {


System.out.println(Arrays.toString(encodeArray(0)));
System.out.println(Arrays.toString(encodeArray(1)));
System.out.println(Arrays.toString(encodeArray(-1)));
System.out.println(Arrays.toString(encodeArray(100001)));
System.out.println(Arrays.toString(encodeArray(999)));
}

static int[] encodeArray(int n) {


if (n == 0)
return new int[]{1};

int size = n < 0 ? 1 : 0;


int nCopy = n < 0 ? -n : n;

while (nCopy > 0) {


int digit = nCopy % 10;
nCopy /= 10;
size += digit + 1;
}

int[] result = new int[size];

nCopy = n < 0 ? -n : n;
for (int i = 0; i < size; i++) {
if (i == 0 && n < 0) {
result[i] = -1;
i++;
}
while (nCopy > 0) {
int digit = nCopy % 10;
nCopy /= 10;

for (int j = 0; j < digit; j++) {


result[i] = 0;
i++;
}
result[i] = 1;
i++;
}
}
return result;
}
}

1. An array is called systematically increasing if it consists of increasing sequences of the


numbers from 1 to n. The first six (there are over 65,000 of them) systematically increasing
arrays are:

{1}
{1, 1, 2}
{1, 1, 2, 1, 2, 3}
{1, 1, 2, 1, 2, 3, 1, 2, 3, 4}
{1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5}
{1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6}

Write a function named isSystematicallyIncreasing which returns 1 if its array


argument is systematically increasing. Otherwise it returns 0.

If you are programming in Java or C#, the function signature is int


isSystematicallyIncreasing(int[ ] a)
If you are programming in C or C++, the function signature is int isSystematicallyIncreasing(int
a[ ], int len) where len is the number of elements in the array a.
Examples
then function
a is reason
returns
{1} 1 because 1 is a sequence from 1 to 1 and is the only sequence.
{1, 2, 1, 2, 3} 0 because it is missing the sequence from 1 to 1.
{1, 1, 3} 0 because {1, 3} is not a sequence from 1 to n for any n.
{1, 2, 1, 2, 1, 2} 0 because it contains more than one sequence from 1 to 2.
because it is "backwards", i.e., the sequences from 1 to n are not ordered
{1, 2, 3, 1, 2, 1} 0
by increasing value of n
{1, 1, 2, 3} 0 because the sequence {1, 2} is missing (it should precede {1, 2, 3})
public class SystematicallyIncreasing {

public static void main(String[] args) {


System.out.println(isSystematicallyIncreasing(new int[]{1}));
System.out.println(isSystematicallyIncreasing(new int[]{1, 1, 2}));
System.out.println(isSystematicallyIncreasing(new int[]
{1, 1, 2, 1, 2, 3}));
System.out.println(isSystematicallyIncreasing(new int[]
{1, 1, 2, 1, 2, 3, 1, 2, 3, 4}));
System.out.println(isSystematicallyIncreasing(new int[]
{1, 2, 1, 2, 3, 1, 2, 3, 4}));
System.out.println(isSystematicallyIncreasing(new int[]
{1, 1, 2, 3}));
}

static int isSystematicallyIncreasing(int[] a) {


int index = 0;
int i = 0;
do {
for (int j = 1; j < i + 1; j++) {
if (a[index] != j)
return 0;
index++;
}
i++;
} while (index < a.length);

return 1;
}
}

2. A positive, non-zero number n is a factorial prime if it is equal to factorial(n’) + 1


for some n and it is prime. Recall that factorial(n) is equal to 1 * 2 * ... * n-1 * n. If
you understand recursion, the recursive definition is
factorial(1) = 1;
factorial(n) = n*factorial(n-1).
For example, factorial(5) = 1*2*3*4*5 = 120.
Recall that a prime number is a natural number which has exactly two distinct
natural number divisors: 1 and itself.
Write a method named isFactorialPrime which returns 1 if its argument is a
factorial prime number, otherwise it returns 0.
The signature of the method is int isFactorialPrime(int n) Examples
if n is Function returns reason
2 1 because 2 is prime and is equal to factorial(1) + 1
3 1 because 3 is prime and is equal to factorial(2) + 1
7 1 because 7 prime and is equal to factorial(3) + 1
8 0 because 8 is not prime
11 0 because 11 does not equal factorial(n) + 1 for any n
(factorial(3)=6, factorial(4)=24)
721 0 because 721 is not prime (its factors are 7 and 103)
public class FactorialPrime {

public static void main(String[] args) {


System.out.println(isFactorialPrime(2));
System.out.println(isFactorialPrime(3));
System.out.println(isFactorialPrime(7));
System.out.println(isFactorialPrime(8));
System.out.println(isFactorialPrime(11));
System.out.println(isFactorialPrime(721));
}

static int isFactorialPrime(int n) {


if (isPrime(n)) {
int sum = 0;
for (int i = 1; i < n && sum < n; i++) {
sum = factorial(i) + 1;
}

if (sum == n) return 1;
else return 0;
}
return 0;
}

static int factorial(int n) {


if (n == 0 || n == 1)
return 1;
else return (n * factorial(n - 1));
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return n > 0;
}
}

3. Write a function named largestDifferenceOfEvens which returns the largest difference between even
valued elements of its array argument. For example largestDifferenceOfEvens(new int[ ]{-2, 3, 4, 9})
returns 6 = (4 - (-2)). If there are fewer than 2 even numbers in the array, largestDifferenceOfEvens
should return -1.
If you are programming in Java or C#, the function signature is int largestDifferenceOfEvens(int[ ] a)
If you are programming in C or C++, the function signature is
int largestDifferenceOfEvens(int a[ ], int len) where len is the number of elements in the array a.
Examples

Function returns
a is reason

{1, 3, 5, 9} -1 because there are no even numbers


because there is only one even number
{1, 18, 5, 7, 33} -1
(18)
because 2-2 == 0
{[2, 2, 2, 2]} 0

because 6 - 2 == 4
{1, 2, 1, 2, 1, 4, 1, 6, 4} 4

public class LargestDifference {

public static void main(String[] args) {


System.out.println(largestDifferenceOfEvens(new int[]{-2, 3,
4, 9}));
System.out.println(largestDifferenceOfEvens(new int[]{1, 3, 5,
9}));
System.out.println(largestDifferenceOfEvens(new int[]{1, 18,
5, 7, 33}));
System.out.println(largestDifferenceOfEvens(new int[]{2, 2, 2,
2}));
System.out.println(largestDifferenceOfEvens(new int[]{1, 2, 1,
2, 1, 4, 1, 6, 4}));
}

static int largestDifferenceOfEvens(int[] a) {


boolean evenFlag = false;
int largestDiff = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
for (int j = i + 1; j < a.length; j++) {
if (a[j] % 2 == 0) {
evenFlag = true;
int diff = a[i] > a[j]? a[i]-a[j]:a[j]-a[i];
largestDiff=diff>largestDiff?diff: largestDiff;
}
}
}
if (!evenFlag && i == a.length - 1)
return -1;
}

return largestDiff;
}
}
1. A hodder number is one that is prime and is equal to 2j-1 for some j. For example,
31 is a hodder number because 31 is prime and is equal to 25-1 (in this case j = 5).
The first 4 hodder numbers are 3, 7, 31, 127
Write a function with signature int isHodder(int n) that returns 1 if n is a hodder
number, otherwise it returns 0.

Recall that a prime number is a whole number greater than 1 that has only two whole
number factors, itself and 1.

public class HolderNumber {

public static void main(String[] args) {


System.out.println(isHolderNumber(3));
System.out.println(isHolderNumber(7));
System.out.println(isHolderNumber(31));
System.out.println(isHolderNumber(127));
}

static int isHolderNumber(int n) {


if (isPrime(n)) {
int number = 0;
int product = 1;

while (number < n) {


product *= 2;
number = product - 1;
}

if (number == n) return 1;
return 0;
}
return 0;
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return n > 0;
}
}

2. One word is an anagram of another word if it is a rearrangement of all the letters


of the second word. For example, the character arrays {'s', 'i', 't'} and {'i', 't', 's'}
represent words that are anagrams of one another because "its" is a rearrangement
of all the letters of "sit" and vice versa. Write a function that accepts two character
arrays and returns 1 if they are anagrams of one another, otherwise it returns 0. For
simplicity, if the two input character arrays are equal, you may consider them to be
anagrams.

If you are programming in Java or C#, the function signature is:


int areAnagrams(char [ ] a1, char [ ] a2)

If you are programming in C or C++, the function signature is


int areAnagrams(a1 char[ ], a2 char[ ], int len) where len is the length of a1 and a2.

Hint: Please note that "pool" is not an anagram of "poll" even though they use the same
letters. Please be sure that your function returns 0 if given these two words! You can
use another array to keep track of each letter that is found so that you don't count the
same letter twice (e.g., the attempt to find the second "o" of "pool" in "poll" should
fail.)

Hint: do not modify either a1 or a2, i.e., your function should have no side effects! If
your algorithm requires modification of either of these arrays, you must work with a
copy of the array and modify the copy!

Examples

if input arrays are return


{'s', 'i', 't'} and {'i', 't', 's'} 1
{'s', 'i', 't'} and {'i', 'd', 's'} 0
{'b', 'i', 'g'} and {'b', 'i', 't'} 0
{'b', 'o', 'g'} and {'b', 'o', 'o'} 0
{} and {} 1
{'b', 'i', 'g'} and {'b', 'i', 'g'} 1

public class Anagrams {

public static void main(String[] args) {


System.out.println(areAnagrams(new char[]
{'s', 'i', 't'}, new char[]{'i', 't', 's'}));
System.out.println(areAnagrams(new char[]
{'s', 'i', 't'}, new char[]{'i', 'd', 's'}));
System.out.println(areAnagrams(new char[]
{'b', 'i', 'g'}, new char[]{'b', 'i', 't'}));
System.out.println(areAnagrams(new char[]
{'b', 'o', 'g'}, new char[]{'b', 'o', 'o'}));
System.out.println(areAnagrams(new char[]{}, new char[]{}));
System.out.println(areAnagrams(new char[]
{'b', 'i', 'g'}, new char[]{'b', 'i', 'g'}));
}

static int areAnagrams(char[] a1, char[] a2) {


if (a1.length != a2.length)
return 0;

char[] a1Copy = new char[a1.length];


char[] a2Copy = new char[a2.length];

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


a1Copy[i] = a1[i];
a2Copy[i] = a2[i];
}

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


for (int j = 0; j < a2Copy.length; j++) {
if (a1Copy[i] == a2Copy[j]) {
a1Copy[i] = ' ';
a2Copy[j] = ' ';
}
}
}

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


if (a1Copy[i] != ' ' || a2Copy[i] != ' ')
return 0;
}

return 1;
}
}

3. The Fibonacci sequence of numbers is 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The first and second numbers are
1 and after that ni = ni-2 + ni-1, e.g., 34 = 13 + 21. A number in the sequence is called a Fibonacci
number. Write a method with signature int closestFibonacci(int n) which returns the largest
Fibonacci number that is less than or equal to its argument. For example, closestFibonacci(13) returns
8 because 8 is the largest Fibonacci number less than 13 and closestFibonacci(33) returns 21 because
21 is the largest Fibonacci number that is <= 33. closestFibonacci(34) should return 34. If the
argument is less than 1 return 0. Your solution must not use recursion because unless you cache the
Fibonacci numbers as you find them, the recursive solution recomputes the same Fibonacci number
many times.

public class ClosestFibonacci {

public static void main(String[] args) {


System.out.println(closestFibonacci(13));
System.out.println(closestFibonacci(12));
System.out.println(closestFibonacci(33));
System.out.println(closestFibonacci(34));
}

static int closestFibonacci(int n) {


int fibonacci = 1;
if (n == 1 || n == 2) {
fibonacci = 1;
}
int fibo1 = 1;
int fibo2 = 1;
for (int i = 3; i <= n; i++) {
fibonacci = fibo1 + fibo2; //Fibonacci number is sum of
previous two Fibonacci number
if (fibonacci > n)
return fibo2;
fibo1 = fibo2;
fibo2 = fibonacci;

return 0;
}
}

1. A number n is vesuvian if it is the sum of two different pairs of squares. For example, 50 is vesuvian
because 50 == 25 + 25 and 1 + 49. The numbers 65 (1+64, 16+49) and 85 (4+81, 36+49) are also
vesuvian. 789 of the first 10,000 integers are vesuvian.

Write a function named isVesuvian that returns 1 if its parameter is a vesuvian number, otherwise it
returns 0. Hint: be sure to verify that your function detects that 50 is a vesuvian number!

public class Vesuvian {

public static void main(String[] args) {


System.out.println(isVesuvian(50));
System.out.println(isVesuvian(65));
System.out.println(isVesuvian(85));
}

static int isVesuvian(int n) {


int count = 0;
for (int i = 1; (i * i) < n; i++) {
int sum1 = i * i;
for (int j = 1; (j * j) < n; j++) {
int sum2 = j * j;

if (sum1 + sum2 == n) {
count++;
break;
}
}
if (count >= 2)
return 1;
}
return 0;
}
}
1. Define an array to be one-balanced if begins with zero or more 1s followed by zero or more
non-1s and concludes with zero or more 1s. Write a function named isOneBalanced that
returns 1 if its array argument is one-balanced, otherwise it returns 0.

If you are programming in Java or C#, the function signature is int isOneBalanced(int[ ] a)
If you are programming in C or C++, the function signature is int isOneBalanced(int a[ ], int
len) where len is the number of elements in the array a. Examples

function
if a is returns reason
{1, 1, 1, 2, 3, -18, 45, 1} 1 because it begins with three 1s, followed by four non-1s and
ends with one 1 and 3+1 == 4
{1, 1, 1, 2, 3, -18, 45, 1, 0} 0 because the 0 starts another sequence of non-1s. There can be
only one sequence of non-1s.
{1, 1, 2, 3, 1, -18, 26, 1} 0 because there are two sequences of non-1s({2, 3} and {-18, 26}
{} 1 because 0 (# of beginning 1s) + 0 (# of ending 1s) =
0 (# of non-1s)
{3, 4, 1, 1} 1 because 0 (# of beginning 1s) + 2 (# of ending 1s) =
2 (# of non-1s)
{1, 1, 3, 4} 1 because 2 (# of beginning 1s) + 0 (# of ending 1s) =
2 (# of non-1s)
{3, 3, 3, 3, 3, 3} 0 because 0 (# of beginning 1s) + 0 (# of ending 1s) !=
6 (# of non-1s)
{1, 1, 1, 1, 1, 1} 0 because 6 (# of beginning 1s) + 0 (# of ending 1s) !=
0 (# of non-1s)

public class OneBalanced {

public static void main(String[] args) {


System.out.println(isOneBalanced(new int[]{1, 1, 1, 2, 3, -18, 45, 1}));
System.out.println(isOneBalanced(new int[]{1, 1, 1, 2, 3, -18, 45, 1, 0}));
System.out.println(isOneBalanced(new int[]{1, 1, 2, 3, 1, -18, 26, 1}));
System.out.println(isOneBalanced(new int[]{}));
System.out.println(isOneBalanced(new int[]{3, 4, 1, 1}));
System.out.println(isOneBalanced(new int[]{1, 1, 3, 4}));
System.out.println(isOneBalanced(new int[]{3, 3, 3, 3, 3, 3}));
System.out.println(isOneBalanced(new int[]{1, 1, 1, 1, 1, 1}));
}

static int isOneBalanced(int[] a) {


int total1s = 0;
int totalNon1s = 0;
boolean non1Start = false;
boolean non1End = false;
if (a.length == 0) return 1;
for (int number : a) {
if (number == 1) {
if (non1Start) non1End = true;
total1s++;
} else {
if (non1End) return 0;
non1Start = true;
totalNon1s++;
}
}
if (total1s != totalNon1s) return 0;
return 1;
}
}

2. The Fibonacci sequence of numbers is 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The first and second numbers are
1 and after that ni
= ni-2 + ni-1, e.g., 34 = 13 + 21. Write a method with signature
int isFibonacci(int n) which returns 1 if its argument is a number in the Fibonacci sequence,
otherwise it returns 0. For example, isFibonacci(13) returns a 1 and isFibonacci(27) returns a 0.
Your solution must not use recursion because unless you cache the Fibonacci numbers as you
find them, the recursive solution recomputes the same Fibonacci number many times.

public class FibonacciNumber {

public static void main(String[] args) {


System.out.println(isFibonacci(1));
System.out.println(isFibonacci(2));
System.out.println(isFibonacci(3));
System.out.println(isFibonacci(4));
System.out.println(isFibonacci(5));
System.out.println(isFibonacci(6));
System.out.println(isFibonacci(7));
System.out.println(isFibonacci(8));
System.out.println(isFibonacci(9));
System.out.println(isFibonacci(10));
System.out.println(isFibonacci(11));
System.out.println(isFibonacci(12));
System.out.println(isFibonacci(13));
}
static int isFibonacci(int n) {
if (n == 1)
return 1;

int fibonacci = 0;
int fibo1 = 1;
int fibo2 = 1;
while (fibonacci < n) {
fibonacci = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = fibonacci;
}

if (fibonacci == n)
return 1;
return 0;
}
}

1. A number n is triangular if n == 1 + 2 +...+j for some j. Write a function int


isTriangular(int n) that returns 1 if n is a triangular number, otherwise it returns 0.
The first 4 triangular numbers are 1 (j=1), 3 (j=2), 6, (j=3), 10 (j=4).

public class TriangularNumber {

public static void main(String[] args) {


System.out.println(isTriangular(1));
System.out.println(isTriangular(3));
System.out.println(isTriangular(4));
System.out.println(isTriangular(6));
System.out.println(isTriangular(10));
System.out.println(isTriangular(11));
System.out.println(isTriangular(12));
System.out.println(isTriangular(13));
System.out.println(isTriangular(14));
System.out.println(isTriangular(15));
}

static int isTriangular(int n) {

int sum = 0;
for (int i = 1; sum < n; i++) {
sum += i;
}
if (sum == n)
return 1;
return 0;
}
}

1. Define an array to be a Mercurial array if a 3 does not occur between any two 1s. Write a
function named isMercurial that returns 1 if its array argument is a Mercurial array, otherwise
it returns 0.

If you are programming in Java or C#, the function signature is int isMercurial(int[ ] a)
If you are programming in C or C++, the function signature is
int isMercurial(int a[ ], int len) where len is the number of elements in the array a.
Hint: if you encounter a 3 that is preceded by a 1, then there can be no more 1s in the array
after the 3. Examples

a is function returns reason


because 3 occurs after a 1 (a[0]) and
{1, 2, 10, 3, 15, 1, 2, 2} 0
before another 1 (a[5])
{5, 2, 10, 3, 15, 1, 2, 2} 1 because the 3 is not between two 1s.
{1, 2, 10, 3, 15, 16, 2, 2} 1 because the 3 is not between two 1s.
because a[5] is a 3 and is between a[3]
{3, 2, 18, 1, 0, 3, -11, 1, 3} 0
and a[7] which are both 1s.
because there are no instances of a 3
{2, 3, 1, 1, 18} 1
that is between two 1s
because there are no instances of a 3
{8, 2, 1, 1, 18, 3, 5} 1
that is between two 1s
because there are no instances of a 3
{3, 3, 3, 3, 3, 3} 1
that is between two 1s
because there are no instances of a 3
{1} 1
that is between two 1s
because there are no instances of a 3
{} 1
that is between two 1s

public class MercurialArray {

public static void main(String[] args) {


System.out.println(isMercurial(new int[]{1,2,10,3,15,1,2, 2}));
System.out.println(isMercurial(new int[]{5, 2, 10, 3, 15, 1, 2, 2}));
System.out.println(isMercurial(new int[]{1,2,10,3,15,16,2,2}));
System.out.println(isMercurial(new int[]{3,2,18,1,0,3,-11,1,3}));
System.out.println(isMercurial(new int[]{2, 3, 1, 1, 18}));
System.out.println(isMercurial(new int[]{8, 2, 1, 1, 18, 3, 5}));
System.out.println(isMercurial(new int[]{3, 3, 3, 3, 3, 3}));
System.out.println(isMercurial(new int[]{1}));
System.out.println(isMercurial(new int[]{}));
}

static int isMercurial(int[] a) {

boolean precedingOneFlag = false;

int indexOf3 = -1;


int indexOf1 = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == 1)
indexOf1 = i;
if (a[i] == 3) {
indexOf3 = i;
}

if (indexOf1 != -1 && indexOf3 > indexOf1)


precedingOneFlag = true;

if (precedingOneFlag && a[i] == 1)


return 0;
}

return 1;
}
}

2. An array is defined to be a 235 array if the number of elements divisible by 2 plus


the number of elements divisible by 3 plus the number of elements divisible by 5
plus the number of elements not divisible by 2, 3, or 5 is equal to the number of
elements of the array. Write a method named is123Array that returns 1 if its array
argument is a 235 array, otherwise it returns 0.

If you are writing in Java or C#, the function signature is int is235Array(int[ ] a)
If you are writing in C or C++, the function signature is int is235Array(int a[ ], int
len) where len is the length of a
Hint: remember that a number can be divisible by more than one number Examples
In the following: <a, b, c, d> means that the array has a elements that are divisible
by 2, b elements that are divisible by 3, c elements that are divisible by 5 and d
elements that are not divisible by 2, 3, or 5.
if a is return reason
because one element is divisible by 2 (a[0]), one is
divisible by 3 (a[1]), one is divisible by 5 (a[2]) and two
{2, 3, 5, 7, 11} 1 are not divisible by 2, 3, or 5 (a[3] and a[4]). So we have
<1, 1, 1, 2> and 1+1+1+2 == the number of elements in
the array.
because two elements are divisible by 2 (a[0] and a[2]),
two are divisible by 3 (a[1] and a[2]), none are divisible
{2, 3, 6, 7, 11} 0 by 5 and two are not divisible by 2, 3, or 5 (a[3] and
a[4]). So we have <2, 2, 0, 2> and 2 + 2 + 0 + 2 == 6 !=
the number of elements in the array.
because <5, 3, 2, 1> and 5 + 3 + 2 + 1 == 11 != the
{2, 3, 4, 5, 6, 7, 8, 9, 10} 0
number of elements in the array.
because <5, 0, 0, 0> and 5 + 0 + 0 + 0 == 5 == the
{2, 4, 8, 16, 32} 1
number of elements in the array.
because <0, 3, 0, 6> and 0 + 3 + 0 + 6 == 9 == the
{3, 9, 27, 7, 1, 1, 1, 1, 1} 1
number of elements in the array.
because <0, 0, 0, 4> and 0 + 0 + 0 + 4 == 4 == the
{7, 11, 77, 49} 1
number of elements in the array.
because <1, 0, 0, 0> and 1 + 0 + 0 + 0 == 1 == the
{2} 1
number of elements in the array.
because <0, 0, 0, 0> and 0 + 0 + 0 + 0 == 0 == the
{} 1
number of elements in the array.
because <4, 1, 0, 6> and 4 + 1 + 0 + 6 == 11 == the
{7, 2, 7, 2, 7, 2, 7, 2, 3, 7, 7} 1
number of elements in the array.
public class Array235 {
public static void main(String[] args) {
System.out.println(is235Array(new int[]{2, 3, 5, 7, 11}));
System.out.println(is235Array(new int[]{2, 3, 6, 7, 11}));
System.out.println(is235Array(new int[]{2,3,4,5,6,7,8,9, 10}));
System.out.println(is235Array(new int[]{2, 4, 8, 16, 32}));
System.out.println(is235Array(new int[]{3,9,27,7,1,1,1,1, 1}));
System.out.println(is235Array(new int[]{7, 11, 77, 49}));
System.out.println(is235Array(new int[]{2}));
System.out.println(is235Array(new int[]{}));
System.out.println(is235Array(new int[]{7,2,7,2,7,2,7,2,3,7, 7}));
}
static int is235Array(int[] a) {
int divisibleBy2 = 0;
int divisibleBy3 = 0;
int divisibleBy5 = 0;

int notDivisible = 0;

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


if (a[i] % 2 == 0 || a[i] % 3 == 0 || a[i] % 5 == 0) {
if (a[i] % 2 == 0)
divisibleBy2++;
if (a[i] % 3 == 0)
divisibleBy3++;
if (a[i] % 5 == 0)
divisibleBy5++;
} else {
notDivisible++;
}
}

if (divisibleBy2+divisibleBy3+divisibleBy5+notDivisible==a.length)
return 1;
return 0;
}
}

3. Write a method named computeHMS that computes the number of hours, minutes and
seconds in a given number of seconds.
If you are programming in Java or C#, the method signature is int[] computeHMS(int
seconds);
If you are programming in C or C++, the method signature is int * computeHMS(int
seconds);
The returned array has 3 elements; arr[0] is the hours, arr[1] is the minutes and arr[2] is the
seconds contained within the seconds argument.
Recall that there are 3600 seconds in an hour and 60 seconds in a minute. You may assume
that the numbers of seconds is non- negative.
Examples
If seconds then function reason
is returns
3735 {1, 2, 15} because 3735 = 1*3600 + 2*60 +15. In other words, 3,735 is the number of
seconds in 1 hour 2
minutes and 15 seconds
380 {0, 6, 20} because 380 = 0*3600 + 6*60 + 20
3650 {1, 0, 50} because 3650 = 1*3600 + 0*60 + 50
55 {0, 0, 55} because 55 = 0*3600 + 0*60 + 55
0 {0, 0, 0} because 0 = 0*3600 + 0*60 + 0

import java.util.Arrays;
public class ComputeHMS {

public static void main(String[] args) {


System.out.println(Arrays.toString(computeHMS(3735)));
System.out.println(Arrays.toString(computeHMS(380)));
System.out.println(Arrays.toString(computeHMS(3650)));
System.out.println(Arrays.toString(computeHMS(55)));
System.out.println(Arrays.toString(computeHMS(0)));
}
static int[] computeHMS(int seconds) {
int[] hms = new int[3];

int hour = 0;
int minute = 0;
int second = 0;

hour = seconds / 3600;


seconds = seconds % 3600;
hms[0] = hour;

minute = seconds / 60;


seconds = seconds % 60;
hms[1] = minute;

second = seconds;
hms[2] = second;

return hms;
}
}

1. Define an array to be a Martian array if the number of 1s is greater than the number
of 2s and no two adjacent elements are equal. Write a function named isMartian that
returns 1 if its argument is a Martian array; otherwise it returns 0.
If you are programming in Java or C#, the function signature is int isMartian(int[ ] a)
If you are programming in C or C++, the function signature is int isMartian(int a[ ],
int len) where len is the number of elements in the array a. There are two additional
requirements.
You should return 0 as soon as it is known that the array is not a Martian array;
continuing to analyze the array would be a waste of CPU cycles. There should be
exactly one loop in your solution. Examples

a is Function returns reason

There is one 1 and zero 2s, hence the number of 1s is


{1, 3} 1 greater than the number of 2s. Also, no adjacent elements
have the same value (1 does not equal 3)
There are five 1s and four 2s, hence the number of 1s is
{1, 2, 1, 2, 1, 2, 1, 2, 1}
1 greater than the number of 2s. Also, no two adjacent
elements have the same value.
There is one 1 and one 2, hence the number of 1s is not
{1, 3, 2} 0
greater than the number of 2s.
{1, 3, 2, 2, 1, 5, 1, 5} 0 There are two 2s adjacent to each other.
The two -18s are adjacent to one another. Note that the
number of 1s is not greater than than the number of 2s but
{1, 2, -18, -18, 1, 2} 0
your method should return 0 before determining that! (See
the additional requirements above.)
There are zero 1s and zero 2s hence the number of 1s is
{} 0
not greater than the number of 2s.
There is one 1 and zero 2s hence the number of 1s is
greater than the number of 2s. Also since there is only one
{1} 1
element, there cannot be adjacent elements with the same
value.
There are zero 1s and one 2 hence the number of 1s is not
{2} 0
greater than the number of 2s.

Hint: Make sure that your solution does not exceed the boundaries of the array!
public class MartianArray {

public static void main(String[] args) {


System.out.println(isMartian(new int[]{1, 3}));
System.out.println(isMartian(new int[]{1,2,1,2,1,2,1, 2, 1}));
System.out.println(isMartian(new int[]{1, 3, 2}));
System.out.println(isMartian(new int[]{1,3,2,2, 1, 5, 1, 5}));
System.out.println(isMartian(new int[]{1,2,-18, -18, 1, 2}));
System.out.println(isMartian(new int[]{}));
System.out.println(isMartian(new int[]{1}));
System.out.println(isMartian(new int[]{2}));
}

static int isMartian(int[] a) {


int countOf1 = 0;
int countOf2 = 0;

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


if (i < a.length - 1 && a[i] == a[i + 1]) {
return 0;
}

if (a[i] == 1)
countOf1++;

if (a[i] == 2)
countOf2++;
}

if (countOf1 > countOf2)


return 1;
return 0;
}
}

2. An array is defined to be paired-N if it contains two distinct elements that sum to N


for some specified value of N and the indexes of those elements also sum to N. Write
a function named isPairedN that returns 1 if its array parameter is a paired-N array,
otherwise it returns 0. The value of N is passed as the second parameter.

If you are writing in Java or C#, the function signature is int isPairedN(int[ ] a, int n)
If you are writing in C or C++, the function signature is int isPairedN(int a[ ], int n,
int len) where len is the length of a There are two additional requirements.
1. Once you know the array is paired-N, you should return 1. No wasted loop iterations please.
2. Do not enter the loop unless you have to. You should test the length of the array
and the value of n to determine whether the array could possibly be a paired-N array.
If the tests indicate no, return 0 before entering the loop.
Examples

if a is and n is return reason


because a[2] + a[3] == 5 and 2+3==5. In other
words, the sum of the values is equal to the sum of
{1, 4, 1, 4, 5, 6} 5 1
the corresponding indexes and both are equal to n
(5 in this case).
{1, 4, 1, 4, 5, 6} 6 1 because a[2] + a[4] == 6 and 2+4==6
{0, 1, 2, 3, 4, 5, 6, 7, 8} 6 1 because a[1]+a[5]==6 and 1+5==6
because although a[0] + a[1] == 5, 0+1 != 5; and
{1, 4, 1} 5 0
although a[1]+a[2]==5, 1+2 != 5
because there are several ways to get the values to
{8, 8, 8, 8, 7, 7, 7} 15 0 sum to 15 but there is no way to get the
corresponding indexes to sum to 15.
{8, -8, 8, 8, 7, 7, -7} -15 0 because although a[1]+a[6]==-15, 1+6!=-15
{3} 3 0 because the array has only one element
{} 0 0 because the array has no elements
public class PairedNArray {

public static void main(String[] args) {


System.out.println(isPairedN(new int[]{1,4, 1,4, 5, 6}, 5));
System.out.println(isPairedN(new int[]{1, 4, 1,4, 5, 6}, 6));
System.out.println(isPairedN(new int[]{0,1,2,3,4,5,6,7,8}, 6);
System.out.println(isPairedN(new int[] {1, 4, 1}, 5));
System.out.println(isPairedN(new int[] {8, 8,8,8,7,7,7}, 15));
System.out.println(isPairedN(new int[]{8,-8,8,8,7,7,-7},-15));
System.out.println(isPairedN(new int[] {3}, 3));
System.out.println(isPairedN(new int[] {}, 0));
}

static int isPairedN(int[] a, int n) {

if (a.length <= 1 || n > a.length + 1 || n < 0)


return 0;

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


for (int j = i + 1; j < a.length; j++) {
if (a[i] + a[j] == n && i + j == n) {
return 1;
}
}
}
return 0;
}
}

This exam tests very basic programming skills and hence will be graded strictly.
However, simple syntax errors will be forgiven. The following examples gives you
an idea of how the exam will be graded.
Sample problem: Write a method int allEven(int a[ ], int len) that returns 1 if all elements of the array a are even,
otherwise it returns Assume that the array has at least one element.

Solution 1:
int allEven (int a[ ], int len)
{
int result = 1;

for (int i=0; i<len && result==1; i++)


{
if (a[i] % 2 == 1)
result = 0; // exit loop, found a non-even element
}

return result;
}
Grading result: Correct; full marks. Will also accept breaking or returning from loop.

Solution 2:
static int allEven (int a[ ], int len)
{
int result = 1;
for (int i=0; i<len; i++)
{
if (a[i] % 2 == 1)
result = 0; // found non-even element
}

return result;
}
Grading result: Correct, but inefficient; marks will be deducted because program continues to loop
even though it is known that the result is 0.

Solution 3
static int allEven (int a[ ], int len)
{
int result = 1;
for (int i=0; i<len; i++)
{
if (a[i] % 2 == 1)
result = 0;
else
result = 1;
}
return result;
}
Grading result: Incorrect; no marks. Program returns status of the last element of the array.

1. Define an array to be n-primeable if for a given n, all elements of the array when
incremented by n are prime. Recall that a prime number is a number that has no factors
except 1 and itself. Write a method named isNPrimeable that has an array parameter and an
integer parameter that defines n; the method returns 1 if its array parameter is n-primeable;
otherwise it returns 0.

If you are programming in Java or C#, the function signature is int isNPrimeable(int[ ] a, int n)

If you are programming in C or C++, the function signature is


int isNPrimeable(int a[ ], int len, int n) where len is the number of elements in the array a. Examples
If a is and n is function returns reason

{5, 15, 27} 2 1 5+2=7 is prime, and 15+2=17 is prime, and 27+2=29 is
prime
{5, 15, 27} 3 0 5+3=8 is not prime
{5, 15, 26} 2 0 26+2=28 is not prime
{1, 1, 1, 1, 1, 1, 1} 4 1 1+4=5 is prime. This obviously holds for all elements in
the array
{} 2 1 Since there are no elements in the array, there cannot exist
one that is non-prime when 2 is added to it.
public class NPrimeable {

public static void main(String[] args) {


System.out.println(isNPrimeable(new int[]{5, 15, 27}, 2));
System.out.println(isNPrimeable(new int[]{5, 15, 27}, 3));
System.out.println(isNPrimeable(new int[]{5, 15, 26}, 2));
System.out.println(isNPrimeable(new int[]{1,1,1,1,1,1,1}, 4));
System.out.println(isNPrimeable(new int[]{}, 2));
}

static int isNPrimeable(int[] a, int n) {


for (int i = 0; i < a.length; i++) {
if (!isPrime(a[i] + n))
return 0;
}
return 1;
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return n > 1;
}
}
2. Define an array to be a 121 array if all elements are either 1 or 2 and the array begins with one or
more 1s followed by a one or more 2s and then ends with the same number of 1s that it begins with.
Write a method named is121Array that returns 1 if its array argument is a 121 array, otherwise, it
returns 0.

If you are programming in Java or C#, the function signature is int is121Array(int[ ] a)

If you are programming in C or C++, the function signature is


int is121Array(int a[ ], int len) where len is the number of

elements in the array a. Examples

then
a reason
function
is
returns
because the same number of 1s are at the beginning and end of
{1, 2, 1} 1
the array and there is at least one 2 in between them.
because the same number of 1s are at the beginning and end of
{1, 1, 2, 2, 2, 1, 1} 1
the array and there is at least one 2 in between them.
Because the number of 1s at the end does not equal the number of
{1, 1, 2, 2, 2, 1, 1, 1} 0
1s at the beginning.
Because the number of 1s at the end does not equal the number of
{1, 1, 1, 2, 2, 2, 1, 1} 0
1s at the beginning.
{1, 1, 1, 2, 2, 2, 1, 1, 1, 3} 0 Because the array contains a number other than 1 and 2.
{1, 1, 1, 1, 1, 1} 0 Because the array does not contain any 2s
{2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1} 0 Because the first element of the array is not a 1.
{1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2} 0 Because the last element of the array is not a 1.
{2, 2, 2} 0 Because there are no 1s in the array.

Hint: Walk through your solution with all the above test cases!

public class Array121 {

public static void main(String[] args) {


System.out.println(is121Array(new int[]{1, 2, 1}));
System.out.println(is121Array(new int[]{1, 1,2, 2, 2, 1, 1}));
System.out.println(is121Array(new int[]{1, 1,2,2,2,1, 1, 1}));
System.out.println(is121Array(new int[]{1,1, 2, 1, 2, 1, 1}));
System.out.println(is121Array(new int[]{1,1,1,2,2,2,1,1,1, 3}));
System.out.println(is121Array(new int[]{1, 1, 1, 1, 1, 1}));
System.out.println(is121Array(new int[]{2,2,2,1,1,1,2,2,2,1, 1}));
System.out.println(is121Array(new int[]{1, 1, 1,2,2,2, 1, 1, 2, 2}));
System.out.println(is121Array(new int[]{2, 2, 2}));
}

static int is121Array(int[] a) {


if (a.length <= 3 || a[0] != 1 || a[a.length - 1] != 1)
return 0;

int i, j;
boolean flag = false;
for (i = 0, j = a.length - 1; i < a.length && j >= 0 && i <=
j; i++, j--) {
if (a[i] != 1 || a[j] != 1) {
if (a[i] != 2 || a[j] != 2)
return 0;
else {
flag = true;
break;
}
}
}

for (int index = i; index <= j; index++) {


if (a[index] != 2)
return 0;
}
if (flag) return 1;
return 0;
}
}
3. Write a method named pairwiseSum that has an array with an even number of
elements as a parameter and returns an array that contains the pairwise sums of
the elements of its parameter array.

If you are writing in Java or C#, the function signature is int[ ] pairwiseSum(int[ ] a)

If you are writing in C or C++, the function signature is


int * pairwiseSum(int a[ ], int len) where len is the length of a The method returns null if
a. The array has no elements
b. The array has an odd number of elements

Otherwise, the method returns an array with arrayLength/2 elements. Each element of the returned array
is the sum of successive pairs of elements of the original array. See examples for more details.

Examples

if a is return reason
because 2+1=3, 18+-5=13. Note that there are
{2, 1, 18, -5} {3, 13} exactly 2 elements in the returned array. You
will lose full marks for this question if you
return {3, 13, 0, 0}!
because 2+1=3, 18+-5=13, -5+-15=-20, 0+0=0,
{2, 1, 18, -5, -5, -15, 0, 0, 1, -1} {3, 13, -20, 0, 0} 1+-1=0.
Note that there are exactly 5 elements in the
returned array. You will lose full marks for this
question if you return {3, 13, -20, 0, 0, 0, 0, 0, 0,
0}!
{2, 1, 18} null because there are an odd number of elements in
the array.
{} null because there are no elements in the array

import java.util.Arrays;

public class PairwiseSum {

public static void main(String[] args) {


System.out.println(Arrays.toString(pairwiseSum(new int[]
{2, 1, 18, -5})));
System.out.println(Arrays.toString(pairwiseSum(new int[]
{2, 1, 18, -5, -5, -15, 0, 0, 1, -1})));
System.out.println(Arrays.toString(pairwiseSum(new int[]
{2, 1, 18})));
System.out.println(Arrays.toString(pairwiseSum(new int[]{})));
}
static int[] pairwiseSum(int[] a) {
if (a.length <= 0 || a.length % 2 != 0)
return null;

int[] result = new int[a.length / 2];

for (int i = 0, index = 0; i < a.length - 1 &&


index < result.length; i = i + 2, index++) {
result[index] = a[i] + a[i + 1];
}

return result;
}
}

1. Write a function named isSquare that returns 1 if its integer argument is a square of
some integer, otherwise it returns 0. Your function must not use any function or
method (e.g. sqrt) that comes with a runtime library or class library! You will
need to write a loop to solve this problem. Furthermore, your method should
return as soon as the status of its parameter is known. So once it is known that
the input parameter is a square of some integer, your method should return 1 and
once it is known that the input is not a square, the method should return 0. There
should be no wasted loop cycles, your method should be efficent!

The signature of the function is int isSquare(int n)

Examples:

if n is return reason

4 1 because 4 = 2*2
25 1 because 25 = 5*5
because there is no integer that when squared equals -4. (note, -2 squared is 4 not
-4 0
-4)
8 0 because the square root of 8 is not an integer.
0 1 because 0 = 0*0
public class IsSquare {

public static void main(String[] args) {


System.out.println(isSquare(4));
System.out.println(isSquare(25));
System.out.println(isSquare(-4));
System.out.println(isSquare(8));
System.out.println(isSquare(0));
}
public static int isSquare(int n) {
if (n < 0)
return 0;

int square = 0;
int number = 1;

while (square < n) {


square = number * number;
number++;
}

if (square == n)
return 1;

return 0;
}
}

2. An array is called complete if it contains an even element, a perfect square and two different
elements that sum to 8. For example, {3, 2, 9, 5} is complete because 2 is even, 9 is a perfect
square and a[0] + a[3] = 8.

Write a function named isComplete that accepts an integer array and returns 1 if it is
a complete array, otherwise it returns 0. Your method must be efficient. It must
return as soon as it is known that the array is complete. Hint: reuse the method
you wrote for question 1.

If you are programming in Java or C#, the function signature is int isComplete(int[ ] a)
If you are programming in C or C++, the function signature is int isComplete(int a[ ], int len)
where len is the number of elements in the array Other examples

if the input array is return reason


{36, -28} 1 36 is even, 36 is a perfect square, 36-28 = 8
{36, 28} 0 There are no two elements that sum to 8
It does not have two different elements that sum to 8 (you
{4} 0
can't use a[0]+a[0])
{3, 2, 1, 1, 5, 6} 0 there is no perfect square.
{3, 7, 23, 13, 107, -99, 97, 81} 0 there is no even number.
public class CompleteArray {

public static void main(String[] args) {


System.out.println(isComplete(new int[]{2,3,2, 4, 11, 6, 10, 9, 8}));
System.out.println(isComplete(new int[]{2, 3,2,4, 11, 8, 10, 9, 8}));
System.out.println(isComplete(new int[]{2, 3, 3, 6}));
System.out.println(isComplete(new int[]{2, -3, 4, 3, 6}));

System.out.println();
System.out.println(isComplete(new int[]{36, -28}));
System.out.println(isComplete(new int[]{36, 28}));
System.out.println(isComplete(new int[]{4}));
System.out.println(isComplete(new int[]{3, 2, 1, 1, 5, 6}));
System.out.println(isComplete(new int[]{3,7,23,13,107,-99,97, 81}));

System.out.println();
System.out.println(isComplete(new int[]{-5,6,2,3,2,4,5, 11, 8, 7}));
System.out.println(isComplete(new int[]{5, 7, 9, 13}));
System.out.println(isComplete(new int[]{2, 2}));
System.out.println(isComplete(new int[]{2, 6, 3, 4}));
}

static int isComplete(int[] a) {


boolean squareFlag = false;
boolean evenFlag = false;
boolean sumFlag = false;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0)
evenFlag = true;

if (a[i] != 1 && IsSquare.isSquare(a[i]) == 1)


squareFlag = true;

for (int j = i + 1; j < a.length; j++) {


if (a[i] + a[j] == 8) {
sumFlag = true;
break;
}
}

if (evenFlag && squareFlag && sumFlag)


return 1;
}

return 0;
}

}
3. Write a function that takes two arguments, an array of integers and a positive, non-
zero number n. It sums n elements of the array starting at the beginning of the array.
If n is greater than the number of elements in the array, the function loops back to
the beginning of the array and continues summing until it has summed n elements.
You may assume that the array contains at least one element and that n is greater
than 0.

If you are programming in Java or C#, the function signature is int loopSum(int[ ] a, int n)
If you are programming in C or C++, the function signature is int loopSum(int a[ ], int len,
int n) where len is the number of elements in the array Examples

and n is
If a is then function returns
{1, 2, 3} 2 3 (which is a[0] + a[1])
-1 (which is a[0] + a[1] + a[2] + a[0] + a[1] +
{-1, 2, -1} 7
a[2] + a[0])
{1, 4, 5, 6} 4 16 (which is a[0] + a[1] + a[2] + a[3])
30
{3} 10
(a[0]+a[0]+a[0]+a[0]+a[0]+a[0]+a[0]+a[0]+a[0]+
a[0])

public class LoopSum {


public static void main(String[] args) {
System.out.println(loopSum(new int[]{1, 2, 3}, 2));
System.out.println(loopSum(new int[]{-1, 2, -1}, 7));
System.out.println(loopSum(new int[]{1, 4, 5, 6}, 4));
System.out.println(loopSum(new int[]{3}, 10));
}

static int loopSum(int[] a, int n) {


int sum = 0;

for (int i=0,index=0;i<a.length && index < n; i++, index++){


sum += a[i];
if (i == a.length - 1 && index != n - 1)
i = -1;
}
return sum;
}
}

1. Write a function named allValuesTheSame that returns 1 if all elements of its argument array have the
same value. Otherwise, it eturns 0. If you are programming in Java or C#, the function signature is int
allValuesTheSame(int[ ] a)

If you are programming in C or C++, the function signature is int allValuesTheSame(int a[ ], int
len) where len is the number of elements in a Examples:

if a is return
{1, 1, 1, 1} 1
{83, 83, 83} 1
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 1
{1, -2343456, 1, -2343456} 0 (because there are two different values, 1 and -2343456)
{0, 0, 0, 0, -1} 0 (because there are two different values, 0 and -1)
{432123456} 1
{-432123456} 1
{} 0

public class AllSameValues {

public static void main(String[] args) {


System.out.println(allValuesTheSame(new int[]{1, 1, 1, 1}));
System.out.println(allValuesTheSame(new int[]{83, 83, 83}));
System.out.println(allValuesTheSame(new int[]
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}));
System.out.println(allValuesTheSame(new int[]
{1, -2343456, 1, -2343456}));
System.out.println(allValuesTheSame(new int[]
{0, 0, 0, 0, -1}));
System.out.println(allValuesTheSame(new int[]{432123456}));
System.out.println(allValuesTheSame(new int[]{-432123456}));
System.out.println(allValuesTheSame(new int[]{}));
}

static int allValuesTheSame(int[] a) {


if (a.length <= 0)
return 0;

for (int i = 0; i < a.length - 1; i++) {


if (a[i] != a[i + 1])
return 0;
}
return 1;
}
}

2. Write a function named hasNValues which takes an array and an integer n as


arguments. It returns true if all the elements of the array are one of n different
values.

If you are writing in Java or C#, the function signature is int hasNValues(int[ ] a, int n)
If you are writing in C or C++, the function signature is int hasNValues(int a[ ], int n,
int len) where len is the length of a
Note that an array argument is passed by reference so that any change you make to the
array in your function will be visible when the function returns. Therefore, you must
not modify the array in your function! In other words, your function should have no
side effects.

Examples

if a is if n is return
{1, 2, 2, 1} 2 1 (because there are 2 different element values, 1 and 2)
{1, 1, 1, 8, 1, 1, 1, 3, 3} 3 1 (because there are 3 different element values, 1, 3, 8)
{1, 2, 3, 4, 5, 6, 7, 8 ,9, 10} 10 1 (because there are 10 different element values)
{1, 2, 2, 1} 3 0 (because there are 2 different element values, not 3 as required)
{1, 1, 1, 8, 1, 1, 1, 3, 3} 2 0 (because there are 3 different element values, not 2 as required)
{1, 2, 3, 4, 5, 6, 7, 8 ,9, 10} 20 0 (because there are 10 different element values, not 20 as required)
Hint: There are many ways to solve this problem. One way is to allocate an array of n
integers and add each unique element found in the array parameter to it. If you add n
elements to the array, return 1, otherwise return 0.

public class NValuesArray {

public static void main(String[] args) {


System.out.println(hasNValues(new int[]
{1, 2, 2, 1}, 2));
System.out.println(hasNValues(new int[]
{1, 1, 1, 8, 1, 1, 1, 3, 3}, 3));
System.out.println(hasNValues(new int[]
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 10));
System.out.println(hasNValues(new int[]{1, 2, 2, 1}, 3));
System.out.println(hasNValues(new int[]
{1, 1, 1, 8, 1, 1, 1, 3, 3}, 2));
System.out.println(hasNValues(new int[]
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 20));
}

static int hasNValues(int[] a, int n) {

if (a.length < n)
return 0;

int[] uniqueArray = new int[n];


int totalAdded = 0;
boolean uniqueFlag;

for (int anA : a) {


uniqueFlag = false;
for (int anUnique : uniqueArray) {
if (anA == anUnique) {
uniqueFlag = true;
break;
}
}
if (!uniqueFlag) {
if (totalAdded >= n)
return 0;
uniqueArray[totalAdded] = anA;
totalAdded++;
}
}

if (totalAdded == n)
return 1;
return 0;
}
}
3. Write a function named sameNumberOfFactors that takes two integer arguments
and returns 1 if they have the same number of factors. If either argument is
negative, return -1. Otherwise return 0.
int sameNumberOfFactors(int n1, int n2)
Examples:
if n1 is and n2 return
is
-6 21 -1 (because one of the arguments is negative)
6 21 1 (because 6 has four factors (1, 2, 3, 6) and so does 21 (1, 3, 7, 21)
8 12 0 (because 8 has four factors(1, 2, 4, 8) and 12 has six factors (1, 2, 3, 4, 6, 12)
23 97 1 (because 23 has two factors (1, 23) and so does 97 (1, 97))
0 1 0 (because 0 has no factors, but 1 has one (1))
0 0 1 (always true if n1 == n2)

public class SameNumberOfFactors {

public static void main(String[] args) {


System.out.println(sameNumberOfFactors(-6, 21));
System.out.println(sameNumberOfFactors(6, 21));
System.out.println(sameNumberOfFactors(8, 12));
System.out.println(sameNumberOfFactors(23, 97));
System.out.println(sameNumberOfFactors(0, 1));
System.out.println(sameNumberOfFactors(0, 0));
}
static int sameNumberOfFactors(int n1, int n2) {
if (n1 < 0 || n2 < 0)
return -1;

if (n1 == n2)
return 1;

int countOfFactor1 = 0;
int countOfFactor2 = 0;

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


if (n1 % i == 0)
countOfFactor1++;
}

for (int j = 1; j <= n2; j++) {


if (n2 % j == 0)
countOfFactor2++;
}

if (countOfFactor1 == countOfFactor2)
return 1;
return 0;
}
}
1. Write a function named eval that returns the value of the polynomial a nxn + an-1 xn-1 + ... +
a1x1 + a0.
If you are programming in Java or C#, the function signature is double eval(double x, int[ ] a)
If you are programming in C or C++, the function signature is double eval(double x, int a[ ], int
len) where len is the number of elements in the array Examples:
if x is if the input array is this represents eval should return
4 3 2
1.0 {0, 1, 2, 3, 4} 4x + 3x + 2x + x + 0 10.0
2
3.0 {3, 2, 1} x + 2x + 3 18.0
2.0 {3, -2, -1} -x2 - 2x + 3 -5.0
2
-3.0 {3, 2, 1} x + 2x + 3 6.0
2.0 {3, 2} 2x + 3 7.0
2
2.0 {4, 0, 9} 9x + 4 40.0
2.0 {10} 10 10.0
10.0 {0, 1} x 10.0
public class Eval {
public static void main(String[] args) {
System.out.println(eval(1.0, new int[]{0, 1, 2, 3, 4}));
System.out.println(eval(3.0, new int[]{3, 2, 1}));
System.out.println(eval(2.0, new int[]{3, -2, -1}));
System.out.println(eval(-3.0, new int[]{3, 2, 1}));
System.out.println(eval(2.0, new int[]{3, 2}));
System.out.println(eval(2.0, new int[]{4, 0, 9}));
System.out.println(eval(2.0, new int[]{10}));
System.out.println(eval(10.0, new int[]{0, 1}));
}
static double eval0(double x, int[] a) {
double sum = 0;
for (int i = a.length - 1; i >= 0; i--) {
double product = 1;
for (int j = 0; j < i; j++) {
product *= x;
}
sum += a[i] * product;
}
return sum;
}
static double eval(double x, int[] a) {
double sum = 0;
for (int i = 0; i < a.length; i++) {
double product = 1;
for (int j = 0; j < i; j++) {
product *= x;
}
sum += a[i] * product;
}
return sum;
}
}
2. A non-empty array a of length n is called an array of all possiblities if it contains all
numbers between 0 and a.length-1 inclusive. Write a method named isAllPossibilities
that accepts an integer array and returns 1 if the array is an array of all possiblities,
otherwise it returns 0.

If you are programming in Java or C#, the function signature is int isAllPossibilities(int[ ] a)

If you are programming in C or C++, the function signature is


int isAllPossibilities(int a[ ], int len) where len is the number of elements in the array Examples

If the input array is return


{1, 2, 0, 3} 1
{3, 2, 1, 0} 1
{1, 2, 4, 3} 0 (because 0 not included and 4 is too big)
{0, 2, 3} 0 (because 1 is not included)
{0} 1
{} 0

Copy and paste your answer here and click the "Submit answer" button

public class AllPossibilitiesArray {

public static void main(String[] args) {


System.out.println(isAllPossibilities(new int[]{1, 2, 0, 3}));
System.out.println(isAllPossibilities(new int[]{3, 2, 1, 0}));
System.out.println(isAllPossibilities(new int[]{1, 2, 4, 3}));
System.out.println(isAllPossibilities(new int[]{0, 2, 3}));
System.out.println(isAllPossibilities(new int[]{0}));
System.out.println(isAllPossibilities(new int[]{}));
}

static int isAllPossibilities1(int[] a) {


if (a.length == 0)
return 0;

int[] tempArray = new int[a.length];

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


tempArray[i] = i;
}

boolean flag = false;


for (int i = 0; i < a.length; i++) {
flag = false;
for (int j = 0; j < tempArray.length; j++) {
if (a[i] == tempArray[j]){
flag = true;
break;
}
}
if (!flag)
return 0;
}
return 1;
}

static int isAllPossibilities(int[] a) {


if (a.length <= 0)
return 0;

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


boolean flag = false;
for (int anA : a) {
if (anA == i) {
flag = true;
break;
}
}
if (!flag)
return 0;
}
return 1;
}
}

3. An array is called layered if its elements are in ascending order and each element
appears two or more times. For example, {1, 1, 2, 2, 2, 3, 3} is layered but {1, 2, 2,
2, 3, 3} and {3, 3, 1, 1, 1, 2, 2} are not. Write a method named isLayered that
accepts an integer array and returns 1 if the array is layered, otherwise it returns 0.

If you are programming in Java or C#, the function signature is int isLayered(int[ ] a)

If you are programming in C or C++, the function signature is


int isLayered(int a[ ], int len) where len is the number of elements in the array Examples:

If the input array is return


{1, 1, 2, 2, 2, 3, 3} 1
{3, 3, 3, 3, 3, 3, 3} 1
{1, 2, 2, 2, 3, 3} 0 (because there is only one occurence of the value 1)
{2, 2, 2, 3, 3, 1, 1} 0 (because values are not in ascending order)
{2} 0
{} 0
Copy and paste your answer here and click the "Submit answer" button

public class LayeredArray {

public static void main(String[] args) {


System.out.println(isLayered(new int[]{1, 1, 2, 2, 2, 3, 3}));
System.out.println(isLayered(new int[]{3, 3, 3, 3, 3, 3, 3}));
System.out.println(isLayered(new int[]{1, 2, 2, 2, 3, 3}));
System.out.println(isLayered(new int[]{2, 2, 2, 3, 3, 1, 1}));
System.out.println(isLayered(new int[]{2}));
System.out.println(isLayered(new int[]{}));
}

static int isLayered(int[] a) {


if (a.length <= 1)
return 0;

int count = 1;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1])
return 0;

if (a[i] == a[i + 1])


count++;

if (a[i] != a[i + 1]) {


if (count < 2)
return 0;
count = 1;
}
}
return 1;
}
}

1. A mileage counter is used to measure mileage in an automobile. A mileage counter looks


something like this
0 599 8
The above mileage counter says that the car has travelled 5,998 miles. Each mile
travelled by the automobile increments the mileage counter. Here is how the above
mileage counter changes over a 3 mile drive.
After the first mile
0 5 99 9
After the second mile
0 600 0
After the third mile
0 600 1
A mileage counter can be represented as an array. The mileage counter
0 599 8
can be represented as the array int a[ ] = new int[ ] {8, 9, 9, 5, 0}
Note that the mileage counter is "backwards" in the array, a[0] represents ones, a[1]
represents tens, a[2] represents hundreds, etc.

Write a function named updateMileage that takes an array representation of a


mileage counter (which can be arbitrarily long) and adds a given number of miles to
the array. Since arrays are passed by reference you can update the array in the
function, you do not have to return the updated array.

You do not have to do any error checking. You may assume that the array contains
non-negative digits and that the mileage is non-negative

If you are programming in Java or C#, the function signature is void updateMileage counter(int[
] a, int miles)
If you are programming in C or C++, the function signature is void updateMileage counter(int a[
], int miles, int len) where len is the number of elements in the array

Examples:
if the input array is and the mileage is the array becomes
{8, 9, 9, 5, 0} 1 {9, 9, 9, 5, 0}
{8, 9, 9, 5, 0} 2 {0, 0, 0, 6, 0}
{9, 9, 9, 9, 9, 9, 9, 9, 9, 9} 1 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
{9, 9, 9, 9, 9, 9, 9, 9, 9, 9} 13 {2, 1, 0, 0, 0, 0, 0, 0, 0, 0}

Note that the mileage counter wraps around if it reaches all 9s and there is still some mileage
to add.

Hint: Write a helper function that adds 1 to the mileage counter and call the helper function once
for each mile Copy and paste your answer here and click the "Submit answer" button

import java.util.Arrays;
public class MileageCounter {

public static void main(String[] args) {


int[] a = new int[]{8, 9, 9, 5, 0};
updateMileageCounter(a, 1);
System.out.println(Arrays.toString(a));
int[] b = new int[]{8, 9, 9, 5, 0};
updateMileageCounter(b, 2);
System.out.println(Arrays.toString(b));
int[] c = new int[]{9, 9, 9, 9, 9, 9, 9, 9, 9, 9};
updateMileageCounter(c, 1);
System.out.println(Arrays.toString(c));
int[] d = new int[]{9, 9, 9, 9, 9, 9, 9, 9, 9, 9};
updateMileageCounter(d, 13);

System.out.println(Arrays.toString(d));
}

static void updateMileageCounter(int[] a, int miles) {


for (int i = 0; i < a.length && miles > 0; i++) {
miles = a[i] + miles;
if (miles > 9) {
int tempMiles = miles % 10;
miles /= 10;
a[i] = tempMiles;
} else {
a[i] = miles;
miles = 0;
}
}
}
}

2. An array is said to be hollow if it contains 3 or more zeros in the middle that are
preceded and followed by the same number of non-zero elements. Furthermore,
all the zeroes in the array must be in the middle of the array. Write a function
named isHollow that accepts an integer array and returns 1 if it is a hollow array,
otherwise it returns 0.
If you are programming in Java or C#, the function signature is int isHollow(int[ ] a)
If you are programming in C or C++, the function signature is int isHollow(int a[ ], int
len) where len is the number of elements in the array Examples:

if the input array is is reason


hollow?
{1,2,0,0,0,3,4} yes 2 non-zeros precede and follow 3 zeros in the middle
{1,1,1,1,0,0,0,0,0,2,1,2,18} yes 4 non-zeros precede and follow the 5 zeros in the middle
{1, 2, 0, 0, 3, 4} no There are only 2 zeroes in the middle; at least 3 are required
{1,2,0,0,0,3,4,5} no The number of preceding non-zeros(2) is not equal to the number of
following non-zeros(3)
{3,8,3,0,0,0,3,3} no The number of preceding non-zeros(3) is not equal to the number of
following non-zeros(2)
{1,2,0,0,0,3,4,0} no Not all zeros are in the middle
{0,1,2,0,0,0,3,4} no Not all zeros are in the middle
{0,0,0} yes The number of preceding non-zeros is 0 which equals the number of
following non-zeros. And there are three zeros "in the middle".
Hint: Write three loops. The first counts the number of preceding non-zeros. The second counts
the number of zeros in the middle. The third counts the number of following non-zeros. Then
analyze the results.

Copy and paste your answer here and click the "Submit answer" button

public class HollowArray {

public static void main(String[] args) {


System.out.println(isHollow(new int[]{1, 2, 0, 0, 0, 3, 4}));
System.out.println(isHollow(new int[]
{1, 1, 1, 1, 0, 0, 0, 0, 0, 2, 1, 2, 18}));
System.out.println(isHollow(new int[]{1, 2, 0, 0, 3, 4}));
System.out.println(isHollow(new int[]
{1, 2, 0, 0, 0, 3, 4, 5}));
System.out.println(isHollow(new int[]
{3, 8, 3, 0, 0, 0, 3, 3}));
System.out.println(isHollow(new int[]
{1, 2, 0, 0, 0, 3, 4, 0}));
System.out.println(isHollow(new int[]
{0, 1, 2, 0, 0, 0, 3, 4}));
System.out.println(isHollow(new int[]
{0, 0, 0}));
}

static int isHollow1(int[] a) {


if (a.length < 3)
return 0;

int precedingNonZeros = 0;
int trailingNonZeros = 0;
int zeros = 0;

int i, j, k;
for (i = 0; i < a.length; i++) {
if (a[i] != 0) {
precedingNonZeros++;
if (i < a.length - 1 && a[i + 1] == 0)
break;
}
if (i < a.length - 1 && a[i] == 0 && a[i + 1] != 0)
return 0;
}
if (precedingNonZeros == a.length - 1)
return 0;

for (j = precedingNonZeros == 0 ? 0 : i + 1; j < a.length;


j++) {
if (a[j] == 0) {
zeros++;
if (j < a.length - 1 && a[j + 1] != 0)
break;
}
}

if (precedingNonZeros + zeros == a.length - 1 || zeros < 3)


return 0;

for (k = j + 1; k < a.length; k++) {


if (a[k] != 0) {
trailingNonZeros++;
if (k < a.length - 1 && a[k + 1] == 0)
return 0;
}
}

if (precedingNonZeros == trailingNonZeros && zeros >= 3)


return 1;
return 0;
}

static int isHollow(int[] a) {


if (a.length < 3)
return 0;
int zeroCount = 0;

for (int i = 0, j = a.length - 1; i <= j; i++, j--) {


if ((a[i] == 0 && a[j] != 0)||(a[i] != 0 && a[j] == 0)){
return 0;
}
if (i == j && a[i] == 0) {
zeroCount++;
} else {
if (a[i] == 0)
zeroCount++;

if (a[j] == 0)
zeroCount++;
}
}

if (zeroCount >= 3) return 1;


return 0;
}
}
3. A positive number n is consecutive-factored if and only if it has factors, i and j where
i > 1, j > 1 and j = i + 1. Write a function named isConsecutiveFactored that returns 1
if its argument is consecutive-factored, otherwise it returns 0.

the function signature is int isConsectiveFactored(int n) Examples:

If n is return because
24 1 24 = 2*3*4 and 3 = 2 + 1
105 0 105 = 3*5*7 and 5 != 3+1 and 7 != 5+1
90 1 factors of 90 include 2 and 3 and 3 = 2 + 1
23 0 has only 1 factor that is not equal to 1
15 0 15 = 3*5 and 5 != 3 + 1
2 0 2 = 1*2, 2 = 1 + 1 but factor 1 is not greater than 1
0 0 n has to be positive
-12 0 n has to be positive

Copy and paste your answer here and click the "Submit answer" button

public class ConsecutiveFactored {

public static void main(String[] args) {


// System.out.println(isConsecutiveFactored(24));
//System.out.println(isConsecutiveFactored(105));
System.out.println(isConsecutiveFactored(90));
//System.out.println(isConsecutiveFactored(23));
//System.out.println(isConsecutiveFactored(15));
//System.out.println(isConsecutiveFactored(2));
//System.out.println(isConsecutiveFactored(0));
//System.out.println(isConsecutiveFactored(-12));
}

static int isConsecutiveFactored(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0 && n % (i + 1) == 0){
System.out.println(i);
return 1;
}
}
return 0;
}
}

1. A twin prime is a prime number that differs from another prime number by 2.
Write a function named isTwinPrime with an integer parameter that returns 1 if
the parameter is a twin prime, otherwise it returns 0. Recall that a prime number is
a number with no factors other than 1 and itself.
the function signature is int isTwinPrime(int n)

Examples:

number is twin prime?


5 yes, 5 is prime, 5+2 is prime
7 yes, 7 is prime, 7-2 is prime
53 no, 53 is prime, but neither 53-2 nor 53+2 is prime
9 no, 9 is not prime

public class TwinPrime {

public static void main(String[] args) {


System.out.println(isTwinPrime(5));
System.out.println(isTwinPrime(7));
System.out.println(isTwinPrime(53));
System.out.println(isTwinPrime(9));
}

static int isTwinPrime(int n) {


if (isPrime(n)) {
if (isPrime(n - 2) || isPrime(n + 2))
return 1;
}
return 0;
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return n > 0;
}
}

2. An array is called zero-balanced if its elements sum to 0 and for each positive
element n, there exists another element that is the negative of n. Write a function
named isZeroBalanced that returns 1 if its argument is a zero-balanced array.
Otherwise it returns 0.
If you are writing in Java or C#, the function signature is int isZeroBalanced(int[ ] a)
If you are writing in C or C++, the function signature is int isZeroBalanced(int a[ ], int len)
where len is the number of elements in a Examples:
if a is return
{1, 2, -2, -1} 1 because elements sum to 0 and each positive element has a corresponding negative
element.
{-3, 1, 2, -2, -1, 1 because elements sum to 0 and each positive element has a corresponding negative
3} element.
{3, 4, -2, -3, -2} 0 because even though this sums to 0, there is no element whose value is -4
{0, 0, 0, 0, 0, 0} 1 this is true vacuously; 0 is not a positive number
{3, -3, -3} 0 because it doesn't sum to 0. (Be sure your function handles this array correctly)
{3} 0 because this doesn't sum to 0
{} 0 because it doesn't sum to 0

public class ZeroBalanced {

public static void main(String[] args) {


System.out.println(isZeroBalanced(new int[]{1, 2, -2, -1}));
System.out.println(isZeroBalanced(new int[]{-3, 1, 2, -2, -1, 3}));
System.out.println(isZeroBalanced(new int[]{3, 4, -2, -3, -2}));
System.out.println(isZeroBalanced(new int[]{0, 0, 0, 0, 0, 0}));
System.out.println(isZeroBalanced(new int[]{-3, -3, -3}));
System.out.println(isZeroBalanced(new int[]{3}));
System.out.println(isZeroBalanced(new int[]{}));
}

static int isZeroBalanced(int[] a) {

if (a.length <= 1)
return 0;

int sum = 0;
boolean negativeFlag = false;
for (int i = 0; i < a.length; i++) {
negativeFlag = a[i] <= 0;

sum += a[i];
for (int j = 0; j < a.length; j++) {
if (a[i] > 0 && a[i] == -a[j]) {
negativeFlag = true;
break;
}
}
if (!negativeFlag)
return 0;
}

if (sum == 0) return 1;
return 0;
}
}
1. A BEQ number is one whose cube contains exactly four 6’s. For example, 806 is a
BEQ number because 806*806*806 = 523,606,616 which has four 6’s. But 36 is not
a BEQ number because its cube is 46,656 which has only three 6’s. And neither is
1,118 because its cube is 1,676,676,672 which contains five 6’s. Write a function
named findSmallestBEQ that returns the smallest BEQ number.

The function signature is int findSmallestBEQnumber( )

Hint use modulo base 10 arithmetic and integer division to get the digits of an integer.

public class BEQNumber {

public static void main(String[] args) {


System.out.println(findSmallestBEQNumber());
}

static int findSmallestBEQNumber() {


int beqNumber;
int number = 1;
while (true) {
beqNumber = number * number * number;
int countOf6 = 0;

while (beqNumber > 0) {


int digit = beqNumber % 10;
beqNumber /= 10;
if (digit == 6)
countOf6++;
}
if (countOf6 == 4) {
return number;
}
number++;
}
}
}
1. An array, a, is called zero-limited if the following two conditions hold:
a. a[3*n+1] is 0 for n>=0 where 3*n+1 is less than the number of elements in the
array.
b. if i != 3*n+1 for some n, then a[i] does not equal 0
For example, {1, 0, 5, -1, 0, 2, 3, 0, 8} is zero-limited because
a[3*0+1] = 0, a[3*1+1] = 0 and a[3*2+1] = 0 and all other elements are non-zero.
Write a function named isZeroLimited that returns 1 if its array argument is zero-limited, else it
returns 0.
If you are programming in Java or C#, the function signature is int isZeroLimited(int[ ] a)
Examples

if a is return reason
{0, 0, 0, 0, 0} 0 Only a[1] and a[4] can be 0
{1, 0} 1 a[1] is 0, all other elements are non-zero
{0, 1} 0 a[1] must be 0 (and a[0] cannot be 0)
{5} 1 Note, because the length of the array is 1, there can be
no zero values, since the first one would occur at a[1]
{1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0} 1 Elements a[1], a[4], a[7] and a[10] are 0 and all others
are non zero
{} 1 Since there are no elements, none can fail the condition.

The best answers will make only one pass through the array, i.e, will have only one loop.

public class ZeroLimited {

public static void main(String[] args) {


System.out.println(isZeroLimited(new int[]{0, 0, 0, 0, 0}));
System.out.println(isZeroLimited(new int[]{1, 0}));
System.out.println(isZeroLimited(new int[]{0, 1}));
System.out.println(isZeroLimited(new int[]{5}));
System.out.println(isZeroLimited(new int[]{1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0}));
System.out.println(isZeroLimited(new int[]{}));
}

static int isZeroLimited(int[] a) {


for (int x = 1; x < a.length; x += 3) {
// x = 3 * n + 1 = 1, 4, 7, 10, ...

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


if (i == x) {
if (a[i] != 0)
return 0;
break;
}
if (a[i] == 0)
return 0;
break;
}
}
return 1;
}

static int isZeroLimited(int[] a) {


int n = 0;
for(int i = 0; i < a.length; i++) {
if(i== 3*n +1) {
if(a[i] != 0)
return 0;
n++;
}
else if(a[i] == 0)
return 0;
}
return 1;

}
}
2. An array is called cube-perfect if all its elements are cubes of some integer. For example, {-
1, 1, -8, -27, 8} is cube-perfect because
-1 = -1 * -1 * -1
1=1*1*1
-8 = -2 * -2 * -2
-27 = -3 * -3 * -3
8=2*2*2
But {27, 3} is not cube-perfect because 3 is not the cube of any integer.

Write a function named isCubePerfect that returns 1 if its argument is cube-perfect, otherwise
it returns 0.

If you are programming in Java or C#, the function signature is int isCubePerfect(int[ ] a)

if a is return because
{1, 1, 1, 1} 1 all elements are cubes of 1
{64} 1 64 = 4*4*4
{63} 0 63 is not the cube of any integer
{-1, 0, 1} 1 -1 = -1 * -1 * -1, 0 = 0 * 0 * 0, 1=1 * 1 * 1
{} 1 no elements fail the cube test
{3, 7, 21, 36} 0 3 is not the cube of any integer

public class CubePerfect {

public static void main(String[] args) {


System.out.println(isCubePerfect(new int[]{1, 1, 1, 1}));
System.out.println(isCubePerfect(new int[]{64}));
System.out.println(isCubePerfect(new int[]{63}));
System.out.println(isCubePerfect(new int[]{-1, 0, 1}));
System.out.println(isCubePerfect(new int[]{}));
System.out.println(isCubePerfect(new int[]{3, 7, 21, 36}));
}

static int isCubePerfect(int[] a) {


if (a.length == 0)
return 1;

for (int anA : a) {

anA = anA > 0 ? anA : -anA;


int number = 1;
int cube = 0;
while (cube < anA) {
cube = number * number * number;
number++;
}
if (cube != anA)
return 0;
}
return 1;
}
}

There are three questions on this test. You have two hours
to complete it. Please do your own work.
1. Write a function named countOnes that returns the number of ones in the binary
representation of its argument. For example, countOnes(9) returns 2 because the
binary representation of 9 is 1001.
Some other examples:
countOnes(5) returns 2 because binary 101 equals 5
countOnes(15) returns 4 because binary 1111 equals 15. You may assume that the
argument is greater than 0.
The function prototype is int countOnes(int n);
Hint use modulo and integer arithmetic to count the number of ones.
public class CountOnes {

public static void main(String[] args) {


System.out.println(countOnes(9));
System.out.println(countOnes(5));
System.out.println(countOnes(15));
}

static int countOnes(int n) {


int count=0;

while (n > 0) {
int digit = n%2;
n /=2;
if (digit == 1)
count++;
}
return count;
}
}

1. A Daphne array is an array that contains either all odd numbers or all even numbers.
For example, {2, 4, 2} (only even numbers) and {1, 3, 17, -5} (only odd numbers) are
Daphne arrays but {3, 2, 5} is not because it contains both odd and even numbers. Write
a function named isDaphne that returns 1 if its array argument is a Daphne array.
Otherwise it returns 0.
If you are programming in Java or C#, the function prototype is int isDaphne (int[ ] a);
If you are programming in C or C++, the function prototype is int isDaphne (int a[ ],
int len) where len is the number of elements in the array.
public class DaphneArray {

public static void main(String[] args) {


System.out.println(isDaphne(new int[]{4, 8, 6, 3, 2, 9, 8, 11,
8, 13, 12, 12, 6}));
System.out.println(isDaphne(new int[]{2, 4, 6, 8, 6}));
System.out.println(isDaphne(new int[]{2, 8, 7, 10, -4, 6}));
}

static int isDaphne1(int[] a) {


int headCount = 0;
int tailCount = 0;
boolean oddFlag = false;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
headCount++;
} else {
oddFlag = true;
break;
}
}

for (int j = a.length - 1; j >= 0; j--) {


if (a[j] % 2 == 0) {
tailCount++;
} else {
break;
}
}
if (headCount == tailCount && oddFlag) return 1;
else return 0;
}
// this is better approach
static int isDaphne2(int[] a) {
int headCount = 0;
int tailCount = 0;
boolean oddFlag = false;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) headCount++;
else oddFlag = true;

if (a[a.length - 1 - i] % 2 == 0) tailCount++;

if (headCount != tailCount) return 0;


}

if (oddFlag) return 1;
else return 0;
}

// this is best
static int isDaphne(int[] a) {
boolean oddFlag = false;

for (int i = 0, j = a.length - 1; i <= j; i++, j--) {


if ((a[i] % 2 == 0 && a[j] % 2 != 0) || (a[i] % 2 != 0 &&
a[j] % 2 == 0))
return 0;
if (a[i] % 2 != 0 || a[j] % 2 != 0)
oddFlag = true;
}
if (oddFlag) return 1;
return 0;
}
}

public class DaphneArray1 {

public static void main(String[] args) {


System.out.println(isDaphne(new int[]{2, 4, 2}));
System.out.println(isDaphne(new int[]{1, 3, 17, -5}));
System.out.println(isDaphne(new int[]{3, 2, 5}));
}

static int isDaphne(int[] a) {


if(a.length <=0)
throw new IllegalArgumentException("invalid input");

boolean evenFlag = a[0]%2==0? true:false;


for(int i = 1; i<a.length; i++) {
if(evenFlag && a[i] %2 != 0)
return 0;
if(!evenFlag && a[i] == 0)
return 0;
}

return 1;
}
static int isDaphne0(int[] a) {
boolean evenFlag = false;
boolean oddFlag = false;

for (int anA : a) {


if (anA % 2 == 0) {
evenFlag = true;
} else {
oddFlag = true;
}

if (evenFlag && oddFlag)


return 0;
}
return 1;
}
}

2. An array is defined to be odd-valent if it meets the following two conditions:


a. It contains a value that occurs more than once
b. It contains an odd number
For example {9, 3, 4, 9, 1} is odd-valent because 9 appears more than once and 3 is odd. Other
odd-valent arrays are {3, 3, 3, 3} and {8, 8, 8, 4, 4, 7, 2}

The following arrays are not odd-valent:


{1, 2, 3, 4, 5} - no value appears more than once.
{2, 2, 2, 4, 4} - there are duplicate values but there is no odd value.

Write a function name isOddValent that returns 1 if its array argument is odd-valent,
otherwise it returns 0.
If you are programming in Java or C#, the function prototype is int isOddValent (int[ ] a);

public class OddValent {

public static void main(String[] args) {


System.out.println(isOddValent(new int[]{9, 3, 4, 9, 1}));
System.out.println(isOddValent(new int[]{3, 3, 3, 3}));
System.out.println(isOddValent(new int[]{8, 8, 8, 4, 4, 7, 2}));
System.out.println(isOddValent(new int[]{1, 2, 3, 4, 5}));
System.out.println(isOddValent(new int[]{2, 2, 2, 4, 4}));
}

static int isOddValent(int[] a) {


boolean occurrenceFlag = false;
boolean oddFlag = false;

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


if (a[i] % 2 != 0) {
oddFlag = true;
}
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
occurrenceFlag = true;
break;
}
}
if (oddFlag && occurrenceFlag)
return 1;
}
return 0;
}
}

There are 3 questions on this test. You have 2 hours


to finish it. Please do your own work.
1. A normal number is defined to be one that has no odd factors, except for 1 and possibly
itself. Write a method named isNormal that returns 1 if its integer argument is normal,
otherwise it returns 0.
Examples: 1, 2, 3, 4, 5, 7, 8 are normal numbers. 6 and 9 are not normal numbers since
3 is an odd factor. 10 is not a normal number since 5 is an odd factor. The function
signature is int isNormal(int n)

public class NormalNumber {

public static void main(String[] args) {


System.out.println(isNormal(1));
System.out.println(isNormal(2));
System.out.println(isNormal(3));
System.out.println(isNormal(4));
System.out.println(isNormal(5));
System.out.println(isNormal(6));
System.out.println(isNormal(7));
System.out.println(isNormal(8));
System.out.println(isNormal(9));
}

static int isNormal(int n) {


for (int i = 2; i < n; i++) {
int factor = 0;
if (n % i == 0)
factor = i;

if (factor % 2 != 0)
return 0;
}
return 1;
}
}

2. A non-empty array of length n is called an array of all possibilities, if it contains


all numbers between 0 and n - 1 inclusive. Write a method named
isAllPossibilities that accepts an integer array and returns 1 if the array is an array
of all possibilities, otherwise it returns 0.

Examples {1, 2, 0, 3} is an array of all possibilities, {3, 2, 1, 0} is an array of all


possibilities, {1, 2, 4, 3} is not an array of all possibilities, (because 0 not included and
4 is too big), {0, 2, 3} is not an array of all possibilities, (because 1 is not included), {0}
is an array of all possibilities, {} is not an array of all possibilities (because array is
empty).

If you are programming in Java or C#, the function signature is


int isAllPossibilities(int[ ] a)
If you are programming in C or C++, the function signature is
int isAllPossibilities(int a[ ], int len) where len is the number of elements in the array.

public class AllPossibilitiesArray {

public static void main(String[] args) {


System.out.println(isAllPossibilities(new int[]{1, 2, 0, 3}));
System.out.println(isAllPossibilities(new int[]{3, 2, 1, 0}));
System.out.println(isAllPossibilities(new int[]{1, 2, 4, 3}));
System.out.println(isAllPossibilities(new int[]{0, 2, 3}));
System.out.println(isAllPossibilities(new int[]{0}));
System.out.println(isAllPossibilities(new int[]{}));
}

static int isAllPossibilities1(int[] a) {


if (a.length == 0)
return 0;

int[] tempArray = new int[a.length];

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


tempArray[i] = i;
}

boolean flag = false;


for (int i = 0; i < a.length; i++) {
flag = false;
for (int j = 0; j < tempArray.length; j++) {
if (a[i] == tempArray[j]){
flag = true;
break;
}
}
if (!flag)
return 0;
}
return 1;
}

static int isAllPossibilities(int[] a) {


if (a.length <= 0)
return 0;

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


boolean flag = false;
for (int anA : a) {
if (anA == i) {
flag = true;
break;
}
}
if (!flag)
return 0;
}
return 1;
}
}

3. An array is defined to be a Filter array if it meets the following conditions


a. If it contains 9 then it also contains 11.
b. If it contains 7 then it does not contain 13.
So {1, 2, 3, 9, 6, 11} and {3, 4, 6, 7, 14, 16}, {1, 2, 3, 4, 10, 11, 13} and {3, 6, 5, 5, 13, 6, 13}
are Filter arrays. The following arrays are not Filter arrays: {9, 6, 18} (contains 9 but no 11),
{4, 7, 13} (contains both 7 and 13)

Write a function named isFilter that returns 1 if its array argument is a Filter array, otherwise it
returns 0.
If you are programming in Java or C#, the function signature is int isFilter(int[ ] a)
If you are programming in C or C++, the function signature is int isFilter(int a[ ], int len) where
len is the number of elements in the array.

public class FilterArray {


static int isFilter1(int[] a) {
boolean cond1 = true;
boolean cond2 = true;

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

if (a[i] == 9) {
for (int j = 0; j < a.length; j++) {
if (a[j] == 11) {
cond1 = true;
break;
} else cond1 = false;
}
}

if (a[i] == 7) {
for (int k = 0; k < a.length; k++) {
if (a[k] == 13) {
cond2 = false;
break;
} else cond2 = true;
}
}

if (cond1 && cond2) return 1;


else return 0;
}

static int isFilter(int[] a) {


boolean cond9Flag = false;
boolean cond7Flag = false;
boolean cond11Flag = false;
boolean cond13Flag = false;

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


if (a[i] == 9) {
cond9Flag = true;
} else if (a[i] == 11) {
cond11Flag = true;
} else if (a[i] == 7) {
cond7Flag = true;
} else if (a[i] == 13) {
cond13Flag = true;
}
}

if ((cond9Flag && cond11Flag) || (cond7Flag && !cond13Flag) ||


(!cond9Flag && !cond7Flag))
return 1;
return 0;
}

public static void main(String[] args) {


System.out.println(FilterArray.isFilter(new int[]{1,2,3,9,6, 11}));
System.out.println(FilterArray.isFilter(new int[]{3,4,6,7, 14, 16}));
System.out.println(FilterArray.isFilter(new int[]{1,2,3,4,10,11,13}));
System.out.println(FilterArray.isFilter(new int[]{3,6,5,5,13,6,13}));
System.out.println(FilterArray.isFilter(new int[]{9, 6, 18}));
System.out.println(FilterArray.isFilter(new int[]{4, 7, 13}));
}
}

There are three questions on this test. You have two hours to
complete it. Please do your own work.
1. Write a function named isDigitSum that returns 1 if sum of all digits of the first
argument is less than the second argument and 0 otherwise. For example
isDigitSum(32121,10 ) would return 1 because 3+2+1+2+1 = 9 < 10.
More examples:
isDigitSum(32121,9) returns 0, isDigitSum(13, 6) returns 1, isDigitSum(3, 3) returns 0

The function should return -1 if either argument is negative, so isDigitSum(-543, 3) returns -1.

The function signature is int isDigitSum(int n, int m)

public class DigitSum {

public static void main(String[] args) {


System.out.println(isDigitSum(32121, 10));
System.out.println(isDigitSum(32121, 9));
System.out.println(isDigitSum(13, 6));
System.out.println(isDigitSum(3, 3));
System.out.println(isDigitSum(-543, 3));
}

static int isDigitSum(int n, int m) {


if (n < 0 || m < 0)
return -1;

int sum = 0;

while (n > 0) {
int digit = n % 10;
n /= 10;
sum += digit;
}

if (sum < m) return 1;


return 0;
}
}

There are three questions on this test. You have two hours to complete it. Please
do your own work. You are not allowed to use any methods or functions provided
by the system unless explicitly stated in the question. In particular, you are not
allowed to convert int to a String or vice-versa.

1. An Evens number is an integer whose digits are all even. For example 2426 is an Evens
number but 3224 is not.

Write a function named isEvens that returns 1 if its integer argument is an Evens number
otherwise it returns 0.
The function signature is int isEvens (int n)

public class EvensNumber {

public static void main(String[] args) {


System.out.println(isEvens(2426));
System.out.println(isEvens(3224));
}

static int isEvens(int n) {


while (n > 0) {
int digit = n % 10;
n /= 10;
if (digit % 2 != 0)
return 0;
}
return 1;
}
}
2. An array is defined to be a Magic array if the sum of the primes in the array is
equal to the first element of the array. If there are no primes in the array, the first
element must be 0. So {21, 3, 7, 9, 11 4, 6} is a Magic array because 3, 7, 11 are
the primes in the array and they sum to 21 which is the first element of the array.
{13, 4, 4, 4, 4} is also a Magic array because the sum of the primes is 13 which is
also the first element. Other Magic arrays are {10, 5, 5}, {0, 6, 8, 20} and {3}.
{8, 5, -5, 5, 3} is not a Magic array because the sum of the primes is 5+5+3 = 13.
Note that -5 is not a prime because prime numbers are positive.

Write a function named isMagicArray that returns 1 if its integer array argument
is a Magic array. Otherwise it returns 0.
If you are writing in Java or C#, the function signature is int isMagicArray (int[ ]
a)You may assume that a function named isPrime exists that returns 1 if its int
argument is a prime, otherwise it returns 0. You do not have to write this
function! You are allowed to use it.

public class MagicArray {

public static void main(String[] args) {


System.out.println(isMagicArray(new int[]{21, 3, 7, 9, 11, 4,
6}));
System.out.println(isMagicArray(new int[]{13, 4, 4, 4, 4}));
System.out.println(isMagicArray(new int[]{10, 5, 5}));
System.out.println(isMagicArray(new int[]{0, 6, 8, 20}));
System.out.println(isMagicArray(new int[]{3}));
System.out.println(isMagicArray(new int[]{8, 5, -5, 5, 3}));
}

static int isMagicArray(int[] a) {


if (a.length == 0)
return 0;

int primeSum = 0;

for (int anA : a) {


if (isPrime(anA) == 1)
primeSum += anA;
}
if (a[0] == primeSum)
return 1;
return 0;
}

static int isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return 0;
}
return n > 1 ? 1 : 0;
}
}
3. An array is defined to be complete if the conditions (a), (d) and (e) below hold.
a. The array contains even numbers
b. Let min be the smallest even number in the array.
c. Let max be the largest even number in the array.
d. min does not equal max
e. All numbers between min and max are in the array

For example {-5, 6, 2, 3, 2, 4, 5, 11, 8, 7} is complete because


a. The array contains even numbers
b. 2 is the smallest even number
c. 8 is the largest even number
d. 2 does not equal 8
e. the numbers 3, 4, 5, 6, 7 are in the array.

Examples of arrays that are not complete are:


{5, 7, 9, 13} condition (a) does not hold, there are no even numbers.
{2, 2} condition (d) does not hold
{2, 6, 3, 4} condition (e) does not hold (5 is missing)

Write a function named isComplete that returns 1 if its array argument is a


complete array. Otherwise it returns 0.

If you are writing in Java or C#, the function signature is int isComplete (int[ ] a)

If you are writing in C or C++, the function signature is


int isComplete (int a[ ], int len) where len is the number of elements in the array.

public class CompleteArray {

public static void main(String[] args) {


System.out.println(isComplete(new int[]{2,3, 2,4,11,6,10,9,8}));
System.out.println(isComplete(new int[]{2,3,2,4,11,8,10,9, 8}));
System.out.println(isComplete(new int[]{2, 3, 3, 6}));
System.out.println(isComplete(new int[]{2, -3, 4, 3, 6}));

System.out.println();
System.out.println(isComplete1(new int[]{36, -28}));
System.out.println(isComplete1(new int[]{36, 28}));
System.out.println(isComplete1(new int[]{4}));
System.out.println(isComplete1(new int[]{3, 2, 1, 1, 5, 6}));
System.out.println(isComplete1(new int[]{3,7,23,13,107,-99,97, 81}));
System.out.println();
System.out.println(isComplete2(new int[]{-5, 6,2,3,2,4,5,11, 8, 7}));
System.out.println(isComplete2(new int[]{5, 7, 9, 13}));
System.out.println(isComplete2(new int[]{2, 2}));
System.out.println(isComplete2(new int[]{2, 6, 3, 4}));
}

static int isComplete2(int[] a) {


if (a.length == 0)
return 0;

int smallestEven = Integer.MAX_VALUE - 1;


int largestEven = Integer.MIN_VALUE;
boolean evenFlag = false;

for (int anA : a) {


if (anA % 2 == 0) {
evenFlag = true;
if (anA > largestEven)
largestEven = anA;
if (anA < smallestEven)
smallestEven = anA;
}
}

if ((evenFlag && smallestEven == largestEven) || !evenFlag)


return 0;

for (int e = smallestEven; e <= largestEven; e++) {


boolean flag = false;
for (int anA : a) {
if (anA == e) {
flag = true;
break;
}
}

if (!flag)
return 0;
}

return 1;
}
}
There are three questions on this test. You have two hours to complete it. Please
do your own work. You are not allowed to use any methods or functions provided
by the system unless explicitly stated in the question. In particular, you are not
allowed to convert int to a String or vice-versa.

1. A primeproduct is a positive integer that is the product of exactly two primes


greater than 1. For example, 22 is primeproduct since 22 = 2 times 11 and both 2
and 11 are primes greater than 1. Write a function named isPrimeProduct with an
integer parameter that returns 1 if the parameter is a primeproduct, otherwise it
returns 0. Recall that a prime number is a positive integer with no factors other than
1 and itself.

You may assume that there exists a function named isPrime(int m) that returns 1 if its
m is a prime number. You do not need to write isPrime. You are allowed to use this
function.

The function signature int isPrimeProduct(int n)

public class PrimeProduct {

public static void main(String[] args) {


System.out.println(isPrimeProduct(22));
System.out.println(isPrimeProduct(18));
System.out.println(isPrimeProduct(15));
System.out.println(isPrimeProduct(49));
}

static int isPrimeProduct(int n) {


if (n <= 1)
return 0;
boolean primeProduct = false;
for (int factor = 2; factor < n; factor++) {
if (n % factor == 0) {
int nextFactor = n / factor;
if (nextFactor != factor && isPrime(factor) &&
isPrime(nextFactor)) {
primeProduct = true;
break;
}
}
}

if (primeProduct)
return 1;
return 0;
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return n > 0;
}
}
2. An array is called balanced if its even numbered elements (a[0], a[2], etc.) are
even and its odd numbered elements (a[1], a[3], etc.) are odd.

Write a function named isBalanced that accepts an array of integers and returns 1 if the
array is balanced, otherwise it returns 0.

Examples: {2, 3, 6, 7} is balanced since a[0] and a[2] are even, a[1] and a[3] are odd.
{6, 7, 2, 3, 12} is balanced since a[0], a[2] and a[4] are even, a[1] and a[3] are odd.
{7, 15, 2, 3} is not balanced since a[0] is odd.
{16, 6, 2, 3} is not balanced since a[1] is even.

If you are programming in Java or C#, the function signature is


int isBalanced(int[ ] a)

If you are programming in C or C++, the function signature is


int isBalanced(int a[ ], int len)
where len is the number of elements in the array.

public class BalancedArray {

public static void main(String[] args) {


System.out.println();
System.out.println(isBalanced1(new int[]{2, 3, 6, 7}));
System.out.println(isBalanced1(new int[]{6, 7, 2, 3, 12}));
System.out.println(isBalanced1(new int[]{7, 15, 2, 3}));
System.out.println(isBalanced1(new int[]{16, 6, 2, 3}));
}

static int isBalanced1(int[] a) {


for (int i = 0; i < a.length; i++) {
if ((i % 2==0 && a[i]%2!=0)||(i % 2 !=0 && a[i] % 2 == 0))
return 0;
}
return 1;
}
}

3. An array with an odd number of elements is said to be centered if all elements (except
the middle one) are strictly greater than the value of the middle element. Note that only
arrays with an odd number of elements have a middle element. Write a function named
isCentered that accepts an integer array and returns 1 if it is a centered array, otherwise
it returns 0.
Examples: {5, 3, 3, 4, 5} is not a centered array (the middle element 3 is not strictly less
than all other elements), {3, 2, 1, 4, 5} is centered (the middle element 1 is strictly less
than all other elements), {3, 2, 1, 4, 1} is not centered (the middle element 1 is not strictly
less than all other elements), {3, 2, 1, 1, 4, 6} is not centered (no middle element since
array has even number of elements), {} is not centered (no middle element), {1} is
centered (satisfies the condition vacuously).

If you are programming in Java or C#, the function signature is


int isCentered(int[ ] a)

If you are programming in C or C++, the function signature is


int isCentered(int a[ ], int len)
where len is the number of elements in the array.

public class CenteredArray {

public static void main(String[] args) {


System.out.println(isCentered(new int[]{1, 2, 3, 4, 5}));
System.out.println(isCentered(new int[]{5, 3, 3, 4, 5}));
System.out.println(isCentered(new int[]{3, 2, 1, 4, 5}));
System.out.println(isCentered(new int[]{3, 2, 1, 4, 1}));
System.out.println(isCentered(new int[]{3, 2, 1, 1, 4, 6}));
System.out.println(isCentered(new int[]{}));
System.out.println(isCentered(new int[]{1}));
}

static int isCentered(int[] a) {


if (a.length == 0 || a.length % 2 == 0)
return 0;

int centerIndex = (a.length - 1) / 2;


int centerValue = a[centerIndex];

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


if (i != centerIndex && a[i] <= centerValue)
return 0;
}
return 1;
}
}
There are three questions on this test. You have two hours to complete it.
Please do your own work. You are not allowed to use any methods or functions
provided by the system unless explicitly stated in the question. In particular,
you are not allowed to convert int to a String or vice-versa.

1. Given a positive integer k, another positive integer n is said to have k-small factors if n can be
written as a product u*v where u and v are both less than k. For instance, 20 has 10-small
factors since both 4 and 5 are less than 10 and 4*5 = 20. (For the same reason, it is also true to
say that 20 has 6-small factors, 7-small factors, 8-small factors, etc). However, 22 does not
have 10-small factors since the only way to factor 22 is as 22 = 2 * 11, and 11 is not less than
10.
Write a function hasKSmallFactors with signatuare boolean hasKSmallFactors(int k, int n)

which returns true if n has k-small factors. The function should return false if either k
or n is not positive.

Examples:
hasKSmallFactors(7, 30) is true (since 5*6 = 30 and 5 < 7, 6 < 7).
hasKSmallFactors(6, 14) is false (since the only way to factor 14 is 2*7 = 14 and 7 not
less than 6) hasKSmallFactors(6, 30) is false (since 5*6 = 30, 6 not less than 6; 3 * 10 =
30, 10 not less than 6; 2 *15 = 30, 15 not less than 6)

public class KSmallFactors {

public static void main(String[] args) {


System.out.println(hasKSmallFactors(10, 20));
System.out.println(hasKSmallFactors(6, 20));
System.out.println(hasKSmallFactors(7, 20));
System.out.println(hasKSmallFactors(8, 20));
System.out.println(hasKSmallFactors(10, 22));
System.out.println(hasKSmallFactors(7, 30));
System.out.println(hasKSmallFactors(6, 14));
System.out.println(hasKSmallFactors(6, 30));
}

static boolean hasKSmallFactors(int k, int n) {


if (k <0 || n <0)
return false;
for (int factor = 1; factor < k; factor++) {
if (n % factor == 0) {
int nextFactor = n / factor;
if (nextFactor < k)
return true;
}
}
return false;
}
}

2. Write a function fill with signature int[ ] fill(int[ ] arr, int k, int n) which does the following: It
returns an integer array arr2 of length n whose first k elements are the same as the first k
elements of arr, and whose remaining elements consist of repeating blocks of the first k
elements. You can assume array arr has at least k elements. The function should return null if
either k or n is not positive.

Examples:
fill({1,2,3,5, 9, 12,-2,-1}, 3, 10) returns {1,2,3,1,2,3,1,2,3,1}.
fill({4, 2, -3, 12}, 1, 5) returns {4, 4, 4, 4, 4}.
fill({2, 6, 9, 0, -3}, 0, 4) returns null.

import java.util.Arrays;
public class FillArray {

public static void main(String[] args) {


System.out.println(Arrays.toString(fill(new int[]
{1, 2, 3, 5, 9, 12, -2, -1}, 3, 10)));
System.out.println(Arrays.toString(fill(new int[]
{4, 2, -3, 12}, 1, 5)));
System.out.println(Arrays.toString(fill(new int[]
{2, 6, 9, 0, -3}, 0, 4)));
}

static int[] fill(int[] arr, int k, int n) {


if (k <= 0 || n <= 0)
return null;

int[] arr2 = new int[n];

for (int i = 0; i < n; ) {


for (int j = 0; j < k && i < n; j++) {
arr2[i] = arr[j];
i++;
}
}
return arr2;
}
}
There are 3 questions on this test. You have 2 hours to finish it. Please do
your own work. All you need to write is three functions. Please do not use
any string functions. No sorting allowed. No additional arrays allowed.
Try to write a simple, elegant and correct code.

1. Write a function named minDistance that returns the smallest distance between two
factors of a number. For example, consider 13013 = 1*7*11*13. Its factors are 1, 7, 11,
13 and 13013. minDistance(13013) would return 2 because the smallest distance between
any two factors is 2 (13 - 11 = 2). As another example, minDistance (8) would return 1
because the factors of 8 are 1, 2, 4, 8 and the smallest distance between any two factors is
1 (2 – 1 = 1).

The function signature is int minDistance(int n)

public class MinDistance {

public static void main(String[] args) {


System.out.println(minDistance(13013));
System.out.println(minDistance(8));
}

static int minDistance(int n) {


int previousFactor = 1;
int minDistance = Integer.MAX_VALUE;

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


if (n % i == 0) {
if (i - previousFactor < minDistance)
minDistance = i - previousFactor;

previousFactor = i;
}
}

return minDistance;
}
}
2. A wave array is defined to an array which does not contain two even numbers or two odd
numbers in adjacent locations. So {7, 2, 9, 10, 5}, {4, 11, 12, 1, 6}, {1, 0, 5} and {2} are all wave
arrays. But {2, 6, 3, 4} is not a wave array because the even numbers 2 and 6 are adjacent to each
other.
Write a function named isWave that returns 1 if its array argument is a Wave array,
otherwise it returns 0
If you are programming in Java or C#, the function signature is int isWave (int [ ] a)
If you are programming in C or C++, the function signature is int isWave (int a[ ], int len)
where len is the number of elements in the array.

public class WaveArray {

public static void main(String[] args) {


System.out.println(isWave(new int[]{7, 2, 9, 10, 5}));
System.out.println(isWave(new int[]{4, 11, 12, 1, 6}));
System.out.println(isWave(new int[]{1, 0, 5}));
System.out.println(isWave(new int[]{2}));
System.out.println(isWave(new int[]{2, 6, 3, 4}));
}

static int isWave(int[] a) {


for (int i = 0; i < a.length - 1; i++) {
if ((a[i] % 2 == 0 && a[i + 1] % 2 == 0) || (a[i] % 2 == 1
&& a[i + 1] % 2 == 1))
return 0;
}
return 1;
}
}

3. An array is defined to be a Bean array if it meets the following conditions


a. If it contains a 9 then it also contains a 13.
b. If it contains a 7 then it does not contain a 16.

So {1, 2, 3, 9, 6, 13} and {3, 4, 6, 7, 13, 15}, {1, 2, 3, 4, 10, 11, 12} and {3, 6, 9, 5, 7, 13, 6, 17}
are Bean arrays. The following arrays are not Bean arrays:
{ 9, 6, 18} (contains a 9 but no 13)
{4, 7, 16} (contains both a 7 and a 16)

Write a function named isBean that returns 1 if its array argument is a Bean array, otherwise it
returns 0.
If you are programming in Java or C#, the function signature is int isBean (int[ ] a)
If you are programming in C or C++, the function signature is
int isBean (int a[ ], int len) where len is the number of elements in the array.
public class BeanArray {

public static void main(String[] args) {

System.out.println();
System.out.println(isBean(new int[]{1, 2, 3, 9, 6, 13}));
System.out.println(isBean(new int[]{3, 4, 6, 7, 13, 15}));
System.out.println(isBean(new int[]{1, 2, 3, 4, 10, 11, 12}));
System.out.println(isBean(new int[]{3, 6, 9, 5, 7, 13, 6, 17}));
System.out.println(isBean(new int[]{9, 6, 18}));
System.out.println(isBean(new int[]{4, 7, 16}));

static int isBean1(int[] a) {


boolean flag9 = false;
boolean flag13 = false;
boolean flag7 = false;
boolean flag16 = false;

for (int anA : a) {


if (anA == 9)
flag9 = true;
else if (anA == 13)
flag13 = true;
else if (anA == 7)
flag7 = true;
else if (anA == 16)
flag16 = true;
}

if ((flag9 && flag13)||(flag7 && !flag16)||(!flag9 && !flag7))


return 1;
return 0;
}

There are three questions on this test. You have two hours to complete it. Please do
your own work. You are not allowed to use any methods or functions provided by
the system unless explicitly stated in the question. In particular, you are not allowed
to convert int to a String or vice-versa.

1. Write a function named countDigit that returns the number of times that a given digit
appears in a positive number. For example countDigit(32121, 1) would return 2
because there are two 1s in 32121.
Other examples:
countDigit(33331, 3) returns 4
countDigit(33331, 6) returns 0
countDigit(3, 3) returns 1

The function should return -1 if either argument is negative, so countDigit(-543, 3) returns -1.

The function signature is int countDigit(int n, int digit)

Hint: Use modulo base 10 and integer arithmetic to isolate the digits of the number.

public class CountDigit {

public static void main(String[] args) {


System.out.println(countDigit(32121, 1));
System.out.println(countDigit(33331, 3));
System.out.println(countDigit(33331, 6));
System.out.println(countDigit(3, 3));
}

static int countDigit(int n, int digit) {


if (n < 0 || digit < 0)
return -1;

int digitCount = 0;

while (n > 0) {
int d = n % 10;
n /= 10;
if (d == digit)
digitCount++;
}
return digitCount;
}
}

2. A Bunker array is defined to be an array in which at least one odd number is immediately
followed by a prime number. So {4, 9, 6, 7, 3} is a Bunker array because the odd number 7 is
immediately followed by the prime number 3. But {4, 9, 6, 15, 21} is not a Bunker array
because none of the odd numbers are immediately followed by a prime number.

Write a function named isBunkerArray that returns 1 if its array argument is a Bunker
array, otherwise it returns 0.
If you are programming in Java or C#, the function signature is int isBunkerArray(int [ ]
a)
If you are programming in C or C++, the function signature is int isBunkerArray(int a[ ],
int len) where len is the number of elements in the array.
You may assume that there exists a function isPrime that returns 1 if it argument is a
prime, otherwise it returns 0. You do not have to write this function.
public class BunkerArray {
public static void main(String[] args) {
System.out.println(isBunkerArray(new int[]{4, 9, 6, 7, 3}));
System.out.println(isBunkerArray(new int[]{4, 9, 6, 15, 21}));

System.out.println();
System.out.println(isBunker(new int[]{7, 6, 10, 1}));
System.out.println(isBunker(new int[]{7, 6, 10}));
System.out.println(isBunker(new int[]{6, 10, 1}));
System.out.println(isBunker(new int[]{3, 7, 1, 8, 1}));
}

static int isBunkerArray(int[] a) {


for (int i = 0; i < a.length - 1; i++) {
if (a[i] % 2 == 1 && isPrime(a[i + 1]) == 1)
return 1;
}
return 0;
}

static int isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return 0;
}
return n > 1 ? 1 : 0;
}

3. A Meera array is defined to be an array such that for all values n in the array, the value 2*n is
not in the array. So {3, 5, -2} is a Meera array because 3*2, 5*2 and -2*2 are not in the array.
But {8, 3, 4} is not a Meera array because for n=4, 2*n=8 is in the array.

Write a function named isMeera that returns 1 if its array argument is a Meera array.
Otherwise it returns 0.
If you are programming in Java or C#, the function signature is int isMeera(int [ ] a)
If you are programming in C or C++, the function signature is int isMeera(int a[ ], int len)
where len is the number of elements in the array.

public class MeeraArray {

public static void main(String[] args) {


System.out.println();
System.out.println(isMeera1(new int[]{3, 5, -2}));
System.out.println(isMeera1(new int[]{8, 3, 4}));
System.out.println();

}
static int isMeera1(int[] a) {
for (int a1 : a) {
for (int a2 : a) {
if (a1 == a2 * 2)
return 0;
}
}
return 1;
}

There are three questions on this test. You have two hours to complete it. Please do your
own work. You are not allowed to use any methods or functions provided by the system
unless explicitly stated in the question. In particular, you are not allowed to convert int
to a String or vice-versa.

1. A Meera number is a number such that the number of nontrivial factors is a factor of
the number. For example, 6 is a Meera number because 6 has two nontrivial factors : 2
and 3. (A nontrivial factor is a factor other than 1 and the number). Thus 6 has two
nontrivial factors. Now, 2 is a factor of 6. Thus the number of nontrivial factors is a
factor of 6. Hence 6 is a Meera number. Another Meera number is 30 because 30 has 2,
3, 5, 6, 10, 15 as nontrivial factors. Thus 30 has 6 nontrivial factors. Note that 6 is a
factor of 30. So 30 is a Meera Number. However 21 is not a Meera number. The
nontrivial factors of 21 are 3 and 7. Thus the number of nontrivial factors is 2. Note
that 2 is not a factor of 21. Therefore, 21 is not a Meera number.
Write a function named isMeera that returns 1 if its integer argument is a Meera
number, otherwise it returns 0.

The signature of the function is int isMeera(int n)

public class MeeraNumber {

public static void main(String[] args) {


System.out.println(isMeera(6));
System.out.println(isMeera(30));
System.out.println(isMeera(21));
}

static int isMeera(int n) {


int factorCount = 0;
for (int i = 2; i < n; i++) {
if (n % i == 0)
factorCount++;
}
if (n % factorCount == 0) return 1;
return 0;
}
}
2. A Bunker array is an array that contains the value 1 if and only if it contains a prime number.
The array {7, 6, 10, 1} is a Bunker array because it contains a prime number (7) and also
contains a 1. The array {7, 6, 10} is not a Bunker array because it contains a prime number
(7) but does not contain a 1. The array {6, 10, 1} is not a Bunker array because it contains a 1
but does not contain a prime number.

It is okay if a Bunker array contains more than one value 1 and more than one prime, so the
array {3, 7, 1, 8, 1} is a Bunker array (3 and 7 are the primes).
Write a function named isBunker that returns 1 if its array argument is a Bunker array and
returns 0 otherwise.
You may assume the existence of a function named isPrime that returns 1 if its argument is a
prime and returns 0 otherwise. You do not have to write isPrime, you can just call it.

If you are programming in Java or C#, the function signature is int isBunker(int [ ] a)

public class BunkerArray {


public static void main(String[] args) {

System.out.println();
System.out.println(isBunker(new int[]{7, 6, 10, 1}));
System.out.println(isBunker(new int[]{7, 6, 10}));
System.out.println(isBunker(new int[]{6, 10, 1}));
System.out.println(isBunker(new int[]{3, 7, 1, 8, 1}));
}

static int isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return 0;
}
return n > 1 ? 1 : 0;
}

static int isBunker(int[] a) {


boolean oneFlag = false;
boolean primeFlag = false;

for (int anA : a) {


if (anA == 1)
oneFlag = true;

if (isPrime(anA) == 1)
primeFlag = true;
}

if ((oneFlag && primeFlag) || (!oneFlag && !primeFlag))


return 1;
return 0;
}
3. A Nice array is defined to be an array where for every value n in the array,
there is also an element n-1 or n+1 in the array.
For example, {2, 10, 9, 3} is a Nice array because
2 = 3-1
10 = 9+1
3=2+1
9 = 10 -1
Other Nice arrays include {2, 2, 3, 3, 3}, {1, 1, 1, 2, 1, 1} and {0, -1, 1}.
The array {3, 4, 5, 7} is not a Nice array because of the value 7 which requires that
the array contains either the value 6 (7-1) or 8 (7+1) but neither of these values are in
the array.

Write a function named isNice that returns 1 if its array argument is a Nice array.
Otherwise it returns a 0.
If you are programming in Java or C#, the function signature is int isNice(int[ ] a)
If you are programming in C or C++, the function signature is int isNice(int a[ ], int
len) where len is the number of elements in the array.

public class NiceArray {

public static void main(String[] args) {


System.out.println(isNice(new int[]{2, 10, 9, 3}));
System.out.println(isNice(new int[]{2, 2, 3, 3, 3}));
System.out.println(isNice(new int[]{1, 1, 1, 2, 1, 1}));
System.out.println(isNice(new int[]{0, -1, 1}));
System.out.println(isNice(new int[]{3, 4, 5, 7}));
}
static int isNice(int[] a) {
for (int a1 : a) {
boolean niceFlag = false;
for (int a2 : a) {
if (a2 == a1 - 1 || a2 == a1 + 1) {
niceFlag = true;
break;
}
}
if (!niceFlag)
return 0;
}
return 1;
}

There are 3 questions on this test. You have two hours to finish it. Please do your
own work. All you need to write is two functions. Please do not use any string
methods. No sorting allowed. No additional data structures including arrays
allowed. Try to write a simple, elegant and correct code.
1. An integer is defined to be “continuous factored” if it can be expressed as the
product of two or more continuous integers greater than 1.
Examples of “continuous factored” integers are:
6 = 2 * 3.
60 = 3 * 4 * 5
120 = 4 * 5 * 6
90 = 9*10
Examples of integers that are NOT “continuous factored” are: 99 = 9*11, 121=11*11,
2=2, 13=13

Write a function named isContinuousFactored(int n) that returns 1 if n is


continuous factored and 0 otherwise.

public class ContinuousFactored {

public static void main(String[] args) {


System.out.println(isContinuousFactored(6));
System.out.println(isContinuousFactored(60));
System.out.println(isContinuousFactored(120));
System.out.println(isContinuousFactored(90));
System.out.println(isContinuousFactored(121));
System.out.println(isContinuousFactored(2));
System.out.println(isContinuousFactored(13));
}

static int isContinuousFactored(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0 && n % (i + 1) == 0)
return 1;
}
return 0;
}
}

2. Consider the prime number 11. Note that 13 is also a prime and 13 – 11 = 2. So,
11 and 13 are known as twin primes. Similarly, 29 and 31 are twin primes. So
is 71 and 73. However, there are many primes for which there is no twin.
Examples are 23, 67. A twin array is defined to an array which every prime
that has a twin appear with a twin. Some examples are
{3, 5, 8, 10, 27}, // 3 and 5 are twins and both are present
{11, 9, 12, 13, 23}, // 11 and 13 are twins and both are present, 23 has no twin
{5, 3, 14, 7, 18, 67}. // 3 and 5 are twins, 5 and 7 are twins, 67 has no twin
The following are NOT twin arrays:
{13, 14, 15, 3, 5} // 13 has a twin prime and it is missing in the array
{1, 17, 8, 25, 67}// 17 has a twin prime and it is missing in the array
Write a function named isTwin(int[ ] arr) that returns 1 if its array argument is a Twin array,
otherwise it returns 0.
public class TwinArray {

public static void main(String[] args) {


System.out.println(isTwin(new int[]{3, 5, 8, 10, 27}));
System.out.println(isTwin(new int[]{11, 9, 12, 13, 23}));
System.out.println(isTwin(new int[]{5, 3, 14, 7, 18, 67}));
System.out.println(isTwin(new int[]{13, 14, 15, 3, 5}));
System.out.println(isTwin(new int[]{1, 17, 8, 25, 67}));
}
static int isTwin(int[] a) {
boolean twinPrimeFlag;
for (int a1 : a) {
twinPrimeFlag = true;
if (isPrime(a1) && (isPrime(a1 - 2) || isPrime(a1 + 2))){
twinPrimeFlag = false;
for (int a2 : a) {
if (isPrime(a1 - 2) && a2 == a1 - 2) {
twinPrimeFlag = true;
break;
}

if (isPrime(a1 + 2) && a2 == a1 + 2) {
twinPrimeFlag = true;
break;
}
}
}
if (!twinPrimeFlag)
return 0;
}
return 1;
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return n > 1;
}
}

3. Let us define two arrays as “set equal” if every element in one is also in the other and
vice-versa. For example, any two of the following are equal to one another: {1, 9, 12},
{12, 1, 9}, {9, 1, 12, 1}, {1, 9, 12, 9, 12, 1, 9}. Note that {1, 7, 8} is not set equal to {1, 7,
1} or {1, 7, 6}.

Write a function named isSetEqual(int[ ] a, int[ ] b) that returns 1 if its array arguments
are set equal, otherwise it returns 0.
public class SetEqual {

public static void main(String[] args) {


System.out.println(isSetEqual(new int[]{9,1,12,1},
new int[]{1, 9, 12, 9, 12, 1, 9}));
System.out.println(isSetEqual(new int[]{9, 1, 12, 1},
new int[]{1, 9, 12, 9, 12, 1, 9, 10}));
System.out.println(isSetEqual(new int[]{1, 7, 8},
new int[]{1, 7, 1}));
System.out.println(isSetEqual(new int[]{1, 7, 8},
new int[]{1, 7, 6}));
}

static int isSetEqual(int[] a, int[] b) {


for (int anA : a) {
boolean flag = false;
for (int aB : b) {
if (aB == anA) {
flag = true;
break;
}
}
if (!flag)
return 0;
}

for (int aB : b) {
boolean flag = false;
for (int anA : a) {
if (aB == anA) {
flag = true;
break;
}
}
if (!flag)
return 0;
}

return 1;
}
}
There are 3 questions on this test. You have two hours to finish it. Please do your
own work. All you need to write is two functions. Please do not use any string
methods. No sorting allowed. No additional data structures including arrays
allowed. Try to write a simple, elegant and correct code.

1. An integer is defined to be a Smart number if it is an element in the infinite sequence 1, 2, 4,


7, 11, 16 … Note that 2-1=1, 4-2=2, 7-4=3, 11-7=4, 16-11=5 so for k>1, the kth element of
the sequence is equal to the k-1th element + k-1. For example, for k=6, 16 is the kth element
and is equal to 11 (the k- 1th element) + 5 ( k-1).

Write function named isSmart that returns 1 if its argument is a Smart number,
otherwise it returns 0. So isSmart(11) returns 1, isSmart(22) returns 1 and isSmart(8)
returns 0.
The function signature is int isSmart(int n)

public class SmartNumber {

public static void main(String[] args) {


System.out.println(isSmart(11));
System.out.println(isSmart(22));
System.out.println(isSmart(8));
}

static int isSmart(int n) {


int previousElement = 1;
int index = 0;
int element = 0;

while (element < n) {


element = previousElement + index;
previousElement = element;
index++;
}

if (element == n) return 1;
return 0;
}
}

2. An array is defined to be a Nice array if the sum of the primes in the array is equal to the
first element of the array. If there are no primes in the array, the first element must be 0. So
{21, 3, 7, 9, 11 4, 6} is a Nice array because 3, 7, 11 are the primes in the array and they sum
to 21 which is the first element of the array. {13, 4, 4,4, 4} is also a Nice array because the
sum of the primes is 13 which is also the first element. Other Nice arrays are {10, 5, 5}, {0, 6,
8, 20} and {3}. {8, 5, -5, 5, 3} is not a Nice array because the sum of the primes is 5+5+3 =
13 but the first element of the array is 8. Note that -5 is not a prime because prime numbers
are positive.
Write a function named isNiceArray that returns 1 if its integer array argument is a Nice array. Otherwise
it returns 0.
The function signature is int isNiceArray (int[ ] a)
You may assume that a function named isPrime exists that returns 1 if its int argument
is a prime, otherwise it returns 0. You do **not** have to write this function! You just
have to call it.
public class NiceArray {
public static void main(String[] args) {
System.out.println();
System.out.println(isNice(new int[]{21, 3, 7, 9, 11, 4, 6}));
System.out.println(isNice(new int[]{13, 4, 4, 4, 4}));
System.out.println(isNice(new int[]{10, 5, 5}));
System.out.println(isNice(new int[]{0, 6, 8, 20}));
System.out.println(isNice(new int[]{3}));
System.out.println(isNice(new int[]{8, 5, -5, 5, 3}));
}
static int isNice(int[] a) {
int primeSum = 0;

for (int anA : a) {


if (isPrime(anA) == 1)
primeSum += anA;
}
if (a[0] == primeSum) return 1;
return 0;
}
static int isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return 0;
}
return n > 1 ? 1 : 0;
}
}
3. An array is defined to be complete if all its elements are greater than 0 and all even numbers
that are less than the maximum even number are in the array.
For example {2, 3, 2, 4, 11, 6, 10, 9, 8} is complete because
a. all its elements are greater than 0
b. the maximum even integer is 10
c. all even numbers that are less than 10 (2, 4, 6, 8) are in the array.

But {2, 3, 3, 6} is not complete because the even number 4 is missing. {2, -3, 4, 3, 6}
is not complete because it contains a negative number.
Write a function named isComplete that returns 1 if its array argument is a complete
array. Otherwise it returns 0.
public class CompleteArray {
public static void main(String[] args) {
System.out.println(isComplete(new int[]{2,3,2, 4, 11, 6, 10, 9, 8}));
System.out.println(isComplete(new int[]{2, 3, 2,4,11, 8, 10, 9, 8}));
System.out.println(isComplete(new int[]{2, 3, 3, 6}));
System.out.println(isComplete(new int[]{2, -3, 4, 3, 6}));
}

static int isComplete(int[] a) {


int maximumEven = Integer.MIN_VALUE;
for (int anA : a) {
if (anA < 0) {
return 0;
}
if (anA % 2 == 0 && anA > maximumEven) {
maximumEven = anA;
}
}
if (maximumEven != 10)
return 0;

for (int i = 2; i < maximumEven; i++) {


if (i % 2 == 0) {
boolean flag = false;

for (int anA : a) {


if (anA == i) {
flag = true;
break;
}
}
if (!flag)
return 0;
}
}

return 1;
}
There are 3 questions on this test. You have two hours to finish it. Please do your
own work. All you need to write is three functions. Please do not use any string
methods. No sorting allowed. No additional data structures including arrays
allowed. Try to write a simple, elegant and correct code.

1. Two integers are defined to be factor equal, if they have the same number of factors. For example,
integers 10 and 33 are factor equal because, 10 has four factors: 1, 2, 5, 10 and 33 also has four
factors: 1, 3, 11, 33. On the other hand, 9 and 10 are not factor equal since 9 has only three factors:
1, 3, 9 and 10 has four factors: 1, 2, 5, 10.
Write a function named factorEqual(int n, int m) that returns 1 if n and m are factor equal and 0
otherwise. The signature of the function is int factorEqual(int n, int m)

public class FactorEqual {

public static void main(String[] args) {


System.out.println(factorEqual(10, 33));
System.out.println(factorEqual(9, 10));
}

static int factorEqual(int n, int m) {

if (n < 0 || m < 0)
return 0;

int factorsOfN = 2;
int factorsOfM = 2;

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


if (n % i == 0)
factorsOfN++;
}

for (int j = 2; j < m; j++) {


if (m % j == 0)
factorsOfM++;
}

if (factorsOfN == factorsOfM) return 1;


return 0;
}
}

2. Define a Meera array to be an array a if it satisfies two conditions:


(a) a[i] is less than i for i = 0 to a.length-1.
(b) sum of all elements of a is 0.

For example, {-4, 0, 1, 0, 2, 1} is a Meera array because


-4 = a[0] < 0
0 = a[1] < 1
1 = a[2] < 2
0 = a[3] < 3
2 = a[4] < 4
1 = a[5] < 5

and -4 + 0 + 1 + 0 + 2 + 1 = 0
{-8, 0, 0, 8, 0} is not a Meera array because a[3] is 8 which is not less than 3. Thus
condition (a) fails. {-8, 0, 0, 2, 0} is not a Meera array because -8 + 2 = -6 not equal to
zero. Thus condition (b) fails.
Write a function named isMeera that returns 1 if its array argument is a Meera array.
Otherwise it returns 0.
If you are programming in Java or C#, the function signature is int isMeera (int[ ] a)
If you are programming in C or C++, the function signature is
int isMeera (int a[ ], int len) where len is the number of elements in the array.

public class MeeraArray {


public static void main(String[] args) {
System.out.println();
System.out.println(isMeera2(new int[]{-4, 0, 1, 0, 2, 1}));
System.out.println(isMeera2(new int[]{-8, 0, 0, 8, 0}));
System.out.println(isMeera2(new int[]{-8, 0, 0, 2, 0}));

static int isMeera2(int[] a) {


int sum = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] >= i)
return 0;
sum += a[i];
}
if (sum == 0)
return 1;
return 0;
}

3. Define a Triple array to be an array where every value occurs exactly three times.
For example, {3, 1, 2, 1, 3, 1, 3, 2, 2} is a Triple array. The following arrays are not Triple
arrays {2, 5, 2, 5, 5, 2, 5} (5 occurs four times instead of three times)
{3, 1, 1, 1} (3 occurs once instead of three times)
Write a function named isTriple that returns 1 if its array argument is a Triple array.
Otherwise it returns 0.
If you are programming in Java or C#, the function signature is int isTriple (int[ ] a)
If you are programming in C or C++, the function signature is int isTriple (int a[ ], int len)
where len is the number of elements in the array.
public class TripleArray {

public static void main(String[] args) {


System.out.println(isTriple(new int[]{3, 1, 2, 1, 3, 1, 3, 2, 2}));
System.out.println(isTriple(new int[]{2, 5, 2, 5, 5, 2, 5}));
System.out.println(isTriple(new int[]{3, 1, 1, 1}));
}

static int isTriple(int[] a) {


for (int a1 : a) {
int count = 0;
for (int a2 : a) {
if (a1 == a2)
count++;
}

if (count != 3)
return 0;
}
return 1;
}
}

There are 3 questions on this test. You have two hours to finish it. Please do your own
work. All you need to write is three functions. Please do not use any string methods. No
sorting allowed. No additional data structures including arrays allowed. Try to write a
simple, elegant and correct code.

1. A Fibonacci number is a number in the sequence 1, 1, 2, 3, 5, 8, 13, 21,…. Note that


first two Fibonacci numbers are 1 and any Fibonacci number other than the first two is
the sum of the previous two Fibonacci numbers. For example, 2 = 1 + 1, 3 = 2 + 1, 5 =
3 + 2 and so on.
Write a function named isFibonacci that returns 1 if its integer argument is a Fibonacci
number, otherwise it returns 0.

The signature of the function is int isFibonacci (int n)

public class FibonacciNumber {

public static void main(String[] args) {


System.out.println(isFibonacci(1));
System.out.println(isFibonacci(2));
System.out.println(isFibonacci(3));
System.out.println(isFibonacci(4));
System.out.println(isFibonacci(5));
System.out.println(isFibonacci(6));
System.out.println(isFibonacci(7));
System.out.println(isFibonacci(8));
System.out.println(isFibonacci(9));
System.out.println(isFibonacci(10));
System.out.println(isFibonacci(11));
System.out.println(isFibonacci(12));
System.out.println(isFibonacci(13));
}

static int isFibonacci(int n) {


if (n == 1)
return 1;

int fibonacci = 0;
int fibo1 = 1;
int fibo2 = 1;

while (fibonacci < n) {


fibonacci = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = fibonacci;
}

if (fibonacci == n) return 1;
return 0;
}
}

2. A Meera array is an array that contains the value 0 if and only if it contains a prime
number. The array {7, 6, 0, 10, 1} is a Meera array because it contains a prime number
(7) and also contains a 0. The array {6, 10, 1} is a Meera array because it contains no
prime number and also contains no 0.

The array {7, 6, 10} is not a Meera array because it contains a prime number (7) but does not
contain a 0. The array {6, 10, 0} is not a Meera array because it contains a 0 but does not
contain a prime number.

It is okay if a Meera array contains more than one value 0 and more than one prime, so the
array {3, 7, 0, 8, 0, 5} is a Meera array (3, 5 and 7 are the primes and there are two zeros.).

Write a function named isMeera that returns 1 if its array argument is a Meera array and returns 0
otherwise.

You may assume the existence of a function named isPrime that returns 1 if its argument is a
prime and returns 0 otherwise. You do not have to write isPrime, you can just call it.

If you are programming in Java or C#, the function signature is


int isMeera(int [ ] a)

If you are are programming in C or C++, the function signature is


int isMeera(int a[ ], int len) where len is the number of elements in the array.

public class MeeraArray {

public static void main(String[] args) {

System.out.println();
System.out.println(isMeera3(new int[]{7, 6, 0, 10, 1}));
System.out.println(isMeera3(new int[]{6, 10, 1}));
System.out.println(isMeera3(new int[]{7, 6, 10}));
System.out.println(isMeera3(new int[]{6, 10, 0}));
System.out.println(isMeera3(new int[]{3, 7, 0, 8, 0, 5}));

static int isMeera3(int[] a) {


boolean primeFlag = false;
boolean zeroFlag = false;

for (int anA : a) {


if (anA == 0)
zeroFlag = true;
if (isPrime(anA) == 1) {
primeFlag = true;
}
}

if ((primeFlag && zeroFlag) || (!primeFlag && !zeroFlag))


return 1;
return 0;
}

static int isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return 0;
}
return n > 1 ? 1 : 0;
}

3. A Bean array is defined to be an array where for every value n in the array, there is
also an element n-1 or n+1 in the array.
For example, {2, 10, 9, 3} is a Bean array because
2 = 3-1
10 = 9+1
3=2+1
9 = 10 -1

Other Bean arrays include {2, 2, 3, 3, 3}, {1, 1, 1, 2, 1, 1} and {0, -1, 1}.

The array {3, 4, 5, 7} is not a Bean array because of the value 7 which requires that the array
contains either the value 6 (7-1) or 8 (7+1) but neither of these values are in the array.

Write a function named isBean that returns 1 if its array argument is a Bean array. Otherwise it returns
a 0.

If you are programming in Java or C#, the function signature is


int isBean(int[ ] a)

If you are programming in C or C++, the function signature is


int isBean(int a[ ], int len) where len is the number of elements in the array.

public class BeanArray {

public static void main(String[] args) {


System.out.println();
System.out.println(isBean2(new int[]{2, 10, 9, 3}));
System.out.println(isBean2(new int[]{2, 2, 3, 3, 3}));
System.out.println(isBean2(new int[]{1, 1, 1, 2, 1, 1}));
System.out.println(isBean2(new int[]{0, -1, 1}));
System.out.println(isBean2(new int[]{3, 4, 5, 7}));

static int isBean2(int[] a) {


for (int a1 : a) {
boolean flag = false;
for (int a2 : a) {
if (a2 == a1 - 1 || a2 == a1 + 1) {
flag = true;
break;
}
}
if (!flag)
return 0;
}
return 1;
}

}
There are 3 questions on this test. You have two hours to finish it. Please do your own
work. All you need to write is three functions. Please do not write main method. If you
write, you are just wasting your time! Please do not use any string methods. No sorting
allowed. No additional data structures including arrays allowed. Try to write a simple,
elegant and correct code.

1. A fancy number is a number in the sequence 1, 1, 5, 17, 61, … .Note that first two fancy
numbers are 1 and any fancy number other than the first two is sum of the three times
previous one and two times the one before that. See below:
1,
1,
3*1 +2*1 = 5
3*5 +2*1 = 17
3*17 + 2*5 = 61
Write a function named isFancy that returns 1 if its integer argument is a Fancy number, otherwise it
returns 0.
The signature of the function is int isFancy(int n)

public class FancyNumber {

public static void main(String[] args) {


System.out.println(isFancy(1));
System.out.println(isFancy(5));
System.out.println(isFancy(17));
System.out.println(isFancy(61));
System.out.println(isFancy(62));
}

static int isFancy(int n) {


if (n == 1)
return 1;

int fancyNumber = 0;
int fancy1 = 1;
int fancy2 = 1;

while (fancyNumber < n) {


fancyNumber = ((fancy1 * 2) + (fancy2 * 3));
fancy1 = fancy2;
fancy2 = fancyNumber;
}
if (fancyNumber == n) return 1;
return 0;
}
}

2. A Meera array is an array that contains the value 1 if and only if it contains 9. The
array {7, 9, 0, 10, 1} is a Meera array because it contains 1 and 9. The array {6, 10, 8}
is a Meera array because it contains no 1 and also contains no 9.
The array {7, 6, 1} is not a Meera array because it contains 1 but does not contain a 9.
The array {9, 10, 0} is not a Meera array because it contains a 9 but does not contain 1.
It is okay if a Meera array contains more than one value 1 and more than one 9, so the
array {1, 1, 0, 8, 0, 9, 9, 1} is a Meera array.
Write a function named isMeera that returns 1 if its array argument is a Meera array and
returns 0 otherwise.
If you are programming in Java or C#, the function signature is int isMeera(int [ ] a)
If you are are programming in C or C++, the function signature is int isMeera(int a[ ], int len) where
len is the number of elements in the array.
static int isMeera4(int[] a) {
boolean flagOf1 = false;
boolean flagOf9 = false;

for (int anA : a) {


if (anA == 1)
flagOf1 = true;
if (anA == 9)
flagOf9 = true;
}

if ((flagOf1 && flagOf9) || (!flagOf1 && !flagOf9))


return 1;
return 0;
}

There are 3 questions on this test. You have two hours to finish it. Please do your
own work. All you need to write is three functions. Please do not write main
method. If you write, you are just wasting your time! Please do not use any string
methods. No sorting allowed. No additional data structures including arrays
allowed. Try to write a simple, elegant and correct code.

1. An integer is defined to be a Bunker number if it is an element in the infinite sequence 1, 2, 4, 7, 11,


16, 22, … Note that 2­1=1, 4­2=2, 7­4=3, 11­7=4, 16­11=5 so for k>1, the kth element of the
sequence is equal to the k-1th element + k-1. E.G., for k=6, 16 is the kth element and is equal to 11
(the k-1th element) + 5 (k-1).
Write function named isBunker that returns 1 if its argument is a Bunker number, otherwise
it returns 0. So isBunker(11) returns 1, isBunker(22) returns 1 and isBunker(8) returns 0

public class BunkerNumber {

public static void main(String[] args) {


System.out.println(isBunker(11));
System.out.println(isBunker(22));
System.out.println(isBunker(8));
}
static int isBunker1(int n) {
if (n == 1) {
return 1;
}

int prevNum = 1;
int num = 0;

for (int i = 1; i < Integer.MAX_VALUE && num <= n; i++) {


num = prevNum + i ;
prevNum = num;
if (num == n) {
return 1;
}
}

return 0;
}

static int isBunker(int n) {


int previousElement = 1;
int index = 0;
int element = 0;

while (element < n) {


element = previousElement + index;
previousElement = element;
index++;
}

if (element == n) return 1;
return 0;
}
}

2. Define a Dual array to be an array where every value occurs exactly twice. For example, {1,
2, 1, 3, 3, 2} is a dual array.
The following arrays are not Dual arrays
{2, 5, 2, 5, 5} (5 occurs three times instead of two times)
{3, 1, 1, 2, 2} (3 occurs once instead of two times)
Write a function named isDual that returns 1 if its array argument is a Dual array. Otherwise
it returns 0.
If you are programming in Java or C#, the function signature is int isDual (int[ ] a)
If you are programming in C or C++, the function signature is
int isDual (int a[ ], int len) where len is the number of elements in the array.
public class DualArray {

public static void main(String[] args) {


System.out.println(isDual(new int[]{1, 2, 1, 3, 3, 2}));
System.out.println(isDual(new int[]{2, 5, 2, 5, 5}));
System.out.println(isDual(new int[]{3, 1, 1, 2, 2}));

System.out.println();
}

static int isDual1(int[] a) {


for (int i = 0; i < a.length; i++) {
int count = 1;
for (int j = 0; j < a.length; j++) {
if (i != j && a[i] == a[j]) {
count++;
}
}

if (count != 2) {
return 0;
}
}

return 1;
}

static int isDual(int[] a) {


for (int a1 : a) {
int count = 0;
for (int a2 : a) {
if (a1 == a2)
count++;
}

if (count != 2)
return 0;
}
return 1;
}
}
There are 3 questions on this test. You have two hours to finish it. Please
do your own work. All you need to write is three functions. Please do not
write main method. If you write, you are just wasting your time! Please do
not use any string methods. No sorting allowed. No additional data
structures including arrays allowed. Try to write a simple, elegant and
correct code.

1. An array is defined to be odd-heavy if it contains at least one odd element and every odd
element is greater than every even element. So {11, 4, 9, 2, 8} is odd- heavy because the two
odd elements (11 and 9) are greater than all the even elements. And {11, 4, 9, 2, 3, 10} is not
odd-heavy because the even element 10 is greater than the odd element 9. Write a function
called isOddHeavy that accepts an integer array and returns 1 if the array is odd-heavy;
otherwise it returns 0. Some other examples: {1} is odd-heavy, {2} is not odd-heavy, {1, 1,
1, 1} is odd-heavy, {2, 4, 6, 8, 11} is odd-heavy, {-2, -4, -6, -8, -11} is not odd-heavy.

If you are programming in Java or C#, the function signature is


int isOddHeavy(int[ ] a)
If you are programming in C or C++, the function signature is
int isOddHeavy(int a[ ], int len)
where len is the number of elements in the array.
package com.knight.exam.java.oddHeavy;

/**
* Created by sachinkeshav on 1/2/15.
*/
public class OddHeavy {

public static void main(String[] args) {


System.out.println(isOddHeavy(new int[]{11, 4, 9, 2, 8}));
System.out.println(isOddHeavy(new int[]{11, 4, 9, 2, 3, 10}));
System.out.println(isOddHeavy(new int[]{1}));
System.out.println(isOddHeavy(new int[]{2}));
System.out.println(isOddHeavy(new int[]{1, 1, 1, 1, 1, 1}));
System.out.println(isOddHeavy(new int[]{2, 4, 6, 8, 11}));
System.out.println(isOddHeavy(new int[]{-2, -4, -6, -8, -11}));
}

static int isOddHeavy(int[] a) {


boolean oddFlag = false;
int smallestOdd = Integer.MAX_VALUE;
int largestEven = Integer.MIN_VALUE;

for (int anA : a) {


if (anA % 2 != 0) {
oddFlag = true;

if (anA < smallestOdd)


smallestOdd = anA;
} else {
if (anA > largestEven)
largestEven = anA;
}
}

if (oddFlag && smallestOdd > largestEven)


return 1;
else return 0;
}
}

2. Question 1. An array with an odd number of elements is said to be centered if all elements
(except the middle one) are strictly greater than the value of the middle element. Note that
only arrays with an odd number of elements have a middle element. Write a function named
isCentered that accepts an integer array and returns 1 if it is a centered array, otherwise it
returns 0. Examples: {1, 2, 3, 4, 5} is not a centered array (the middle element 3 is not
strictly less than all other elements), {3, 2, 1, 4, 5} is centered (the middle element 1 is
strictly less than all other elements), {3, 2, 1, 4, 1} is not centered (the middle element 1 is
not strictly less than all other elements), {3, 2, 1, 1, 4, 6} is not centered (no middle element
since array has even number of elements), {} is not centered (no middle element), {1} is
centered (satisfies the condition vacuously).

If you are programming in Java or C#, the function signature is int isCentered(int[ ] a)
If you are programming in C or C++, the function signature is int isCentered(int a[ ], int len)
where len is the number of elements in the array.

public class CenteredArray {

public static void main(String[] args) {


System.out.println(isCentered(new int[]{1, 2, 3, 4, 5}));
System.out.println(isCentered(new int[]{5, 3, 3, 4, 5}));
System.out.println(isCentered(new int[]{3, 2, 1, 4, 5}));
System.out.println(isCentered(new int[]{3, 2, 1, 4, 1}));
System.out.println(isCentered(new int[]{3, 2, 1, 1, 4, 6}));
System.out.println(isCentered(new int[]{}));
System.out.println(isCentered(new int[]{1}));
}

static int isCentered(int[] a) {


if (a.length == 0 || a.length % 2 == 0)
return 0;

int centerIndex = (a.length - 1) / 2;


int centerValue = a[centerIndex];

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


if (i != centerIndex && a[i] <= centerValue)
return 0;
}
return 1;
}
}

3. An array is said to be dual if it has an even number of elements and each pair of consecutive
even and odd elements sum to the same value. Write a function named isDual that accepts an
array of integers and returns 1 if the array is dual, otherwise it returns 0. Examples: {1, 2, 3,
0} is a dual array (because 1+2 = 3+0 = 3), {1, 2, 2, 1, 3, 0} is a dual array (because 1+2 =
2+1 = 3+0 = 3), {1, 1, 2, 2} is not a dual array (because 1+1 is not equal to 2+2), {1, 2,
1} is not a dual array (because array does not have an even number of elements), {} is a dual
array.
If you are programming in Java or C#, the function signature is int isDual(int[ ] a)
If you are programming in C or C++, the function signature is int isDual(int a[ ], int len)
where len is the number of elements in the array.

public class DualArray {

public static void main(String[] args) {


System.out.println(isDual(new int[]{1, 2, 1, 3, 3, 2}));
System.out.println(isDual(new int[]{2, 5, 2, 5, 5}));
System.out.println(isDual(new int[]{3, 1, 1, 2, 2}));

System.out.println();
System.out.println(isDual2(new int[]{1, 2, 3, 0}));
System.out.println(isDual2(new int[]{1, 2, 2, 1, 3, 0}));
System.out.println(isDual2(new int[]{1, 1, 2, 2}));
System.out.println(isDual2(new int[]{1, 2, 1}));
}

static int isDual2(int[] a) {


if (a.length % 2 != 0 || a.length < 4)
return 0;

int sum = a[0] + a[1];


for (int i = 0; i < a.length - 1; i += 2) {
if (sum != a[i] + a[i + 1])
return 0;
}
return 1;
}
}
There are 3 questions on this test. You have two hours to finish it. Please
do your own work. All you need to write is three functions. Please do not
use any string methods. No sorting allowed. No additional data structures
including arrays allowed. Try to write a simple, elegant and correct code.

1. Write a function named factorTwoCount that returns the number of times that 2 divides
the argument.

For example, factorTwoCount(48) returns 4 because 48/2 = 24


24/2 = 12
12/2 = 6
6/2 = 3
2 does not divide 3 evenly.

Another example: factorTwoCount(27) returns 0 because 2 does not divide 27.


The function signature is int factorTwoCount(int n);

public class FactorTwoCount {

public static void main(String[] args) {


System.out.println(factorTwoCount(48));
System.out.println(factorTwoCount(27));
}

static int factorTwoCount(int n) {


int count = 0;

while (n % 2 == 0) {
count++;
n /= 2;
}

return count;
}
}

2. A Daphne array is defined to be an array that contains at least one odd number and begins
and ends with the same number of even numbers.

So {4, 8, 6, 3, 2, 9, 8,11, 8, 13, 12, 12, 6} is a Daphne array because it begins with three
even numbers and ends with three even numbers and it contains at least one odd number.
The array {2, 4, 6, 8, 6} is not a Daphne array because it does not contain an odd number.
The array {2, 8, 7, 10, -4, 6} is not a Daphne array because it begins with two even
numbers but ends with three even numbers.

Write a function named isDaphne that returns 1 if its array argument is a Daphne array.
Otherwise, it returns 0.
If you are writing in Java or C#, the function signature is int isDaphne (int[ ] a)
If you are writing in C or C++, the function signature is int isDaphne (int a[ ], int len) where len
is the number of elements in the array.

public class DaphneArray {

public static void main(String[] args) {


System.out.println(isDaphne(new int[]
{4, 8, 6, 3, 2, 9, 8, 11, 8, 13, 12, 12, 6}));
System.out.println(isDaphne(new int[]{2, 4, 6, 8, 6}));
System.out.println(isDaphne(new int[]{2, 8, 7, 10, -4, 6}));
}

static int isDaphne1(int[] a) {


int headCount = 0;
int tailCount = 0;
boolean oddFlag = false;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
headCount++;
} else {
oddFlag = true;
break;
}
}

for (int j = a.length - 1; j >= 0; j--) {


if (a[j] % 2 == 0) {
tailCount++;
} else {
break;
}
}
if (headCount == tailCount && oddFlag) return 1;
else return 0;
}

// this is better approach


static int isDaphne2(int[] a) {
int headCount = 0;
int tailCount = 0;
boolean oddFlag = false;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) headCount++;
else oddFlag = true;

if (a[a.length - 1 - i] % 2 == 0) tailCount++;

if (headCount != tailCount) return 0;


}
if (oddFlag) return 1;
else return 0;
}

// this is best
static int isDaphne(int[] a) {
boolean oddFlag = false;

for (int i = 0, j = a.length - 1; i <= j; i++, j--) {


if ((a[i] % 2 == 0 && a[j] % 2 != 0) || (a[i] % 2 != 0 &&
a[j] % 2 == 0))
return 0;
if (a[i] % 2 != 0 || a[j] % 2 != 0)
oddFlag = true;
}
if (oddFlag) return 1;
return 0;
}
}

3. Write a function called goodSpread that returns 1 if no value in its array argument occurs
more than 3 times in the array.

For example, goodSpread(new int[] {2, 1, 2, 5, 2, 1, 5, 9} returns 1 because no value occurs


more than three times.
But goodSpread(new int[ ] {3, 1, 3 ,1, 3, 5, 5, 3} ) returns 0 because the value 3 occurs four
times.
If you are writing in Java or C#, the function signature is int goodSpread (int[ ] a)

If you are writing in C or C++, the function signature is


int goodSpread (int a[ ], int len) where len is the number of elements in the array.
public class GoodSpread {

public static void main(String[] args) {


System.out.println(goodSpread(new int[]{2, 1, 2, 5, 2, 1, 5, 9}));
System.out.println(goodSpread(new int[]{3, 1, 3, 1, 3, 5, 5, 3}));
}

static int goodSpread(int[] a) {


for (int i = 0; i < a.length; i++) {
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[i] == a[j]) {
count++;

if (count > 3)
return 0;
}
}
}

return 1;
}
}

There are 3 questions on this test. You have two hours to finish it. Please do
your own work. All you need to write is three functions. Please do not use
any string methods. No sorting allowed. No additional data structures
including arrays allowed. Try to write a simple, elegant and correct code.
1. Write a function called goodSpread that returns 1 if no value in its array argument occurs more than 3
times in the array.
For example, goodSpread(new int[] {2, 1, 2, 5, 2, 1, 5, 9} returns 1 because no value occurs
more than three times.
But goodSpread(new int[ ] {3, 1, 3 ,1, 3, 5, 5, 3} ) returns 0 because the value 3 occurs four
times.
If you are writing in Java or C#, the function signature is int goodSpread (int[ ] a)
If you are writing in C or C++, the function signature is
int goodSpread (int a[ ], int len) where len is the number of elements in the array.

There are three questions on this test. You have two hours to complete it. Please do your own
work.
public class GoodSpread {

public static void main(String[] args) {


System.out.println(goodSpread(new int[]{2, 1, 2, 5, 2, 1, 5, 9}));
System.out.println(goodSpread(new int[]{3, 1, 3, 1, 3, 5, 5, 3}));
}

static int goodSpread(int[] a) {


for (int i = 0; i < a.length; i++) {
int count = 0;
for (int j = 0; j < a.length; j++) {
if (a[i] == a[j]) {
count++;

if (count > 3) return 0;


}
}
}

return 1;
}
}

2. Write a function named sumDigits that sums the digits of its integer argument. For example
sumDigits(3114) returns 9, sumDigits(-6543) returns 18 and sumDigits(0) returns 0.
The signature of the function is int sumDigits (int n)

public class SumDigits {

public static void main(String[] args) {


System.out.println(sumDigits(3114));
System.out.println(sumDigits(-6543));
}

static int sumDigits(int n) {


if (n < 0)
n = -n;

int sum = 0;

while (n > 0) {
int rem = n % 10;
sum += rem;
n = n / 10;
}

return sum;
}
}

3. Define a Meera array to be an array where a[n] is less than n for n = 0 to a.length-1.
For example, {-4, 0, 1, 0, 2} is a Meera array because
a[0] < 0
a[1] < 1
a[2] < 2
a[3] < 3
a[4] < 4

{-1, 0, 0, 8, 0} is not a Meera array because a[3] is 8 which is not less than 3.
Write a function named isMeera that returns 1 if its array argument is a Meera array. Otherwise it returns
0.
If you are programming in Java or C#, the function signature is int isMeera (int[ ] a)
If you are programming in C or C++, the function signature is
int isMeera (int a[ ], int len) where len is the number of elements in the array.

public class MeeraArray {

public static void main(String[] args) {


System.out.println(isMeera(new int[]{-4, 0, 1, 0, 2}));
System.out.println(isMeera(new int[]{-1, 0, 0, 8, 0}));

static int isMeera(int[] a) {


for (int i = 0; i < a.length; i++) {
if (a[i] >= i)
return 0;
}

return 1;
}

There are three questions on this test. You have two hours to complete it.
Please do your own work.

1. An integer is defined to be a Guthrie number if it is an element in the infinite sequence 1, 2, 4, 7, 11,


16 … Note that 2- 1=1, 4-2=2, 7-4=3, 11-7=4, 16-11=5 so for k>1, the kth element of the sequence is
equal to the k-1th element + k-1. E.G., for k=6, 16 is the kth element and is equal to 11 (the k-1th
element) + k-1.
Write function named isGuthrie that returns 1 if its argument is a Guthrie number, otherwise it returns
0. So isGuthrie(11) returns 1, is Guthrie(22) returns 1 and isGuthrie(8) returns 0
The function signature is int isGuthrie (int n)

public static void main(String[] args) {


System.out.println(isGuthrie(11));
System.out.println(isGuthrie(22));
System.out.println(isGuthrie(8));
}

static int isGuthrie(int n) {


int previousElement = 1;
int index = 0;
int element = 0;

while (element < n) {


element = previousElement + index;
previousElement = element;
index++;
}

if (element == n) return 1;
return 0;
}
}

2. An array is defined to be a Bean array if the sum of the primes in the array is equal to the first
element of the array. If there are no primes in the array, the first element must be 0. So {21, 3, 7, 9, 11
4, 6} is a Bean array because 3, 7, 11 are the primes in the array and they sum to 21 which is the first
element of the array. {13, 4, 4,4, 4} is also a Bean array because the sum of the primes is 13 which is
also the first element. Other Bean arrays are {10, 5, 5}, {0, 6, 8, 20} and {3}.
{8, 5, -5, 5, 3} is not a Bean array because the sum of the primes is 5+5+3 = 13 but the first element
of the array is 8. Note that -5 is not a prime because prime numbers are positive.

Write a function named isBeanArray that returns 1 if its integer array argument is a Bean array.
Otherwise it returns 0.

If you are writing in Java or C#, the function signature is int isBeanArray (int[ ] a)

If you are writing in C or C++, the function signature is


int isBeanArray (int a[ ], int len) where len is the number of elements in the array.
You may assume that a function named isPrime exists that returns 1 if its int argument is a prime,
otherwise it returns 0.

You do **not** have to write this function! You just have to call it.
public class BeanArray {

public static void main(String[] args) {


System.out.println(isBeanArray(new int[]{21, 3, 7, 9, 11, 4, 6}));
System.out.println(isBeanArray(new int[]{13, 4, 4, 4, 4}));
System.out.println(isBeanArray(new int[]{10, 5, 5}));
System.out.println(isBeanArray(new int[]{0, 6, 8, 20}));
System.out.println(isBeanArray(new int[]{3}));
System.out.println(isBeanArray(new int[]{8, 5, -5, 5, 3}));
}

static int isBeanArray(int[] a) {


int a1 = a[0];
int sum = 0;

for (int anA : a) {


if (isPrime(anA)) {
sum += anA;
}
}

if (/*(sum == a[0]) return 1;


else return 0;
}

static boolean isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}

return n > 1;
}

3. An array is defined to be complete if all its elements are greater than 0 and all
even numbers that are less than the maximum even number are in the array.

For example {2, 3, 2, 4, 11, 6, 10, 9, 8} is complete because


a. all its elements are greater than 0
b. the maximum even integer is 10
c. all even numbers that are less than 10 (2, 4, 6, 8) are in the array.

But {2, 3, 3, 6} is not complete because the even number 4 is missing. {2, -3, 4, 3, 6}
is not complete because it contains a negative number.

Write a function named isComplete that returns 1 if its array argument is a complete array.
Otherwise it returns 0.

If you are writing in Java or C#, the function signature is int isComplete (int[ ] a)

If you are writing in C or C++, the function signature is


int isComplete (int a[ ], int len) where len is the number of elements in the array.

public class CompleteArray {

public static void main(String[] args) {


System.out.println(isComplete(new int[]{2,3,2, 4, 11, 6, 10, 9, 8}));
System.out.println(isComplete(new int[]{2, 3, 2, 4,11,8, 10, 9, 8}));
System.out.println(isComplete(new int[]{2, 3, 3, 6}));
System.out.println(isComplete(new int[]{2, -3, 4, 3, 6}));

static int isComplete(int[] a) {


int maximumEven = Integer.MIN_VALUE;

for (int anA : a) {


if (anA < 0) {
return 0;
}

if (anA % 2 == 0 && anA > maximumEven) {


maximumEven = anA;
}
}
if (maximumEven != 10) return 0;

for (int i = 2; i < maximumEven; i++) {


if (i % 2 == 0) {
boolean flag = false;

for (int anA : a) {


if (anA == i) {
flag = true;
break;
}
}
if (!flag)
return 0;
}
}

return 1;
}

There are three questions on this test. You have 2 hours to complete it. Please do
your own work.
1. An integer is defined to be a Bunker number if it is an element in the infinite sequence 1, 2, 4, 7,
11, 16, 22, … Note that 2­1=1, 4­2=2, 7­4=3, 11­7=4, 16­11=5 so for k>1, the kth element of the
sequence is equal to the k-1th element + k-1. E.G., for k=6, 16 is the kth element and is equal to
11 (the k-1th element) + 5 (k-1).

Write function named isBunker that returns 1 if its argument is a Bunker number, otherwise it
returns 0. So isBunker(11) returns 1, isBunker(22) returns 1 and isBunker(8) returns 0

The function signature is int isBunker (int n)

public class BunkerNumber {

public static void main(String[] args) {


System.out.println(isBunker(11));
System.out.println(isBunker(22));
System.out.println(isBunker(8));
}

static int isBunker1(int n) {


if (n == 1) {
return 1;
}

int prevNum = 1;
int num = 0;

for (int i = 2; i < Integer.MAX_VALUE && num <= n; i++) {


num = prevNum + i - 1;
prevNum = num;
if (num == n) {
return 1;
}
}

return 0;
}
static int isBunker(int n) {
int previousElement = 1;
int index = 0;
int element = 0;

while (element < n) {


element = previousElement + index;
previousElement = element;
index++;
}

if (element == n) return 1;
return 0;
}
}
There are 3 questions on this test. You have two hours to finish it. Please do your own
work. All you need to write is three functions. Please do not use any string methods. No
sorting allowed. No additional data structures including arrays allowed. Try to write a
simple, elegant and correct code.

1. A Fibonacci number is a number in the sequence 1, 1, 2, 3, 5, 8, 13, 21,…. Note that first two
Fibonacci numbers are 1 and any Fibonacci number other than the first two is the sum of the previous
two Fibonacci numbers. For example, 2 = 1+ 1, 3 = 2 + 1, 5 = 3 + 2 and so on.

Write a function named isFibonacci that returns 1 if its integer argument is a Fibonacci number,
otherwise it returns 0.
The signature of the function is int isFibonacci (int n)

public class FibonacciNumber {

public static void main(String[] args) {


System.out.println(isFibonacci(1));
System.out.println(isFibonacci(2));
System.out.println(isFibonacci(3));
System.out.println(isFibonacci(4));
System.out.println(isFibonacci(5));
System.out.println(isFibonacci(6));
System.out.println(isFibonacci(7));
System.out.println(isFibonacci(8));
System.out.println(isFibonacci(9));
System.out.println(isFibonacci(10));
System.out.println(isFibonacci(11));
System.out.println(isFibonacci(12));
System.out.println(isFibonacci(13));
}

static int isFibonacci(int n) {


if (n == 1)
return 1;
int fibonacci = 0;
int fibo1 = 1;
int fibo2 = 1;

while (fibonacci < n) {


fibonacci = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = fibonacci;
}

if (fibonacci == n) return 1;
return 0;
}
}

2. A Meera array is an array that contains the value 0 if and only if it contains a prime number.
The array {7, 6, 0, 10, 1} is a Meera array because it contains a prime number (7) and also
contains a 0. The array {6, 10, 1} is a Meera array because it contains no prime number and
also contains no 0.

The array {7, 6, 10} is not a Meera array because it contains a prime number (7) but does not
contain a 0. The array {6, 10, 0} is not a Meera array because it contains a 0 but does not
contain a prime number.

It is okay if a Meera array contains more than one value 0 and more than one prime, so the
array {3, 7, 0, 8, 0, 5} is a Meera array (3, 5 and 7 are the primes and there are two zeros.).

Write a function named isMeera that returns 1 if its array argument is a Meera array and
returns 0 otherwise.

You may assume the existence of a function named isPrime that returns 1 if its argument is a
prime and returns 0 otherwise. You do not have to write isPrime, you can just call it.

If you are programming in Java or C#, the function signature is int isMeera(int [ ] a)

If you are are programming in C or C++, the function signature is


int isMeera(int a[ ], int len) where len is the number of elements in the array.

public class MeeraArray {

public static void main(String[] args) {

System.out.println();
System.out.println(isMeera3(new int[]{7, 6, 0, 10, 1}));
System.out.println(isMeera3(new int[]{6, 10, 1}));
System.out.println(isMeera3(new int[]{7, 6, 10}));
System.out.println(isMeera3(new int[]{6, 10, 0}));
System.out.println(isMeera3(new int[]{3, 7, 0, 8, 0, 5}));

static int isMeera3(int[] a) {


boolean primeFlag = false;
boolean zeroFlag = false;

for (int anA : a) {


if (anA == 0)
zeroFlag = true;
if (isPrime(anA) == 1) {
primeFlag = true;
}
}

if ((primeFlag && zeroFlag) || (!primeFlag && !zeroFlag))


return 1;
return 0;
}

static int isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return 0;
}
return n > 1 ? 1 : 0;
}
There are three questions on this test. You have two hours to complete it.
Please do your own work. You are not allowed to use any methods or
functions provided by the system unless explicitly stated in the question. In
particular, you are not allowed to convert int to a String or vice-versa.

1. A Meera number is a number such that the number of nontrivial factors is a factor of the
number. For example, 6 is a Meera number because 6 has two nontrivial factors : 2 and 3. (A
nontrivial factor is a factor other than 1 and the number). Thus 6 has two nontrivial factors.
Now, 2 is a factor of 6. Thus the number of nontrivial factors is a factor of 6. Hence 6 is a
Meera number. Another Meera number is 30 because 30 has 2, 3, 5, 6, 10, 15 as nontrivial
factors. Thus 30 has 6 nontrivial factors. Note that 6 is a factor of 30. So 30 is a Meera
Number. However 21 is not a Meera number. The nontrivial factors of 21 are 3 and 7. Thus
the number of nontrivial factors is 2. Note that 2 is not a factor of 21. Therefore, 21 is not a
Meera number.
Write a function named isMeera that returns 1 if its integer argument is a Meera number,
otherwise it returns 0.
The signature of the function is int isMeera(int n)

public class MeeraNumber {

public static void main(String[] args) {


System.out.println(isMeera(6));
System.out.println(isMeera(30));
System.out.println(isMeera(21));
}

static int isMeera(int n) {


int factorCount = 0;
for (int i = 2; i < n; i++) {
if (n % i == 0)
factorCount++;
}
if (n % factorCount == 0) return 1;
return 0;
}
}

2. A Bunker array is an array that contains the value 1 if and only if it contains a prime number.
The array {7, 6, 10, 1} is a Bunker array because it contains a prime number (7) and also
contains a 1. The array {7, 6, 10} is not a Bunker array because it contains a prime number
(7) but does not contain a 1. The array {6, 10, 1} is not a Bunker array because it contains a 1
but does not contain a prime number.

It is okay if a Bunker array contains more than one value 1 and more than one prime, so the
array {3, 7, 1, 8, 1} is a Bunker array (3 and 7 are the primes).
Write a function named isBunker that returns 1 if its array argument is a Bunker array and
returns 0 otherwise.

You may assume the existence of a function named isPrime that returns 1 if its argument is a
prime and returns 0 otherwise. You do not have to write isPrime, you can just call it.

If you are programming in Java or C#, the function signature is int isBunker(int [ ] a)
If you are programming in C or C++, the function signature is

int isBunker(int a[ ], int len) where len is the number of elements in the array.
public class BunkerArray {

public static void main(String[] args) {


System.out.println(isBunkerArray(new int[]{4, 9, 6, 7, 3}));
System.out.println(isBunkerArray(new int[]{4, 9, 6, 15, 21}));

System.out.println();
System.out.println(isBunker(new int[]{7, 6, 10, 1}));
System.out.println(isBunker(new int[]{7, 6, 10}));
System.out.println(isBunker(new int[]{6, 10, 1}));
System.out.println(isBunker(new int[]{3, 7, 1, 8, 1}));
}

static int isBunkerArray(int[] a) {


for (int i = 0; i < a.length - 1; i++) {
if (a[i] % 2 == 1 && isPrime(a[i + 1]) == 1)
return 1;
}
return 0;
}

static int isPrime(int n) {


for (int i = 2; i < n; i++) {
if (n % i == 0)
return 0;
}
return n > 1 ? 1 : 0;
}

static int isBunker(int[] a) {


boolean oneFlag = false;
boolean primeFlag = false;

for (int anA : a) {


if (anA == 1)
oneFlag = true;

if (isPrime(anA) == 1)
primeFlag = true;
}

if ((oneFlag && primeFlag) || (!oneFlag && !primeFlag))


return 1;
return 0;
}
}

3. A Pascal number is a number that is the sum of the integers from 1 to j for some j. For
example 6 is a Pascal number because 6 = 1 + 2 + 3. Here j is 3. Another Pascal number is 15
because 15 = 1 + 2 + 3 + 4 + 5. An example of a number that is not a Pascal number is 7
because it falls between the Pascal numbers 6 and 10.

Write a function named isPascal that returns 1 if its integer argument is a Pascal number, otherwise it
returns 0. The signature of the function is int isPascal (int n)

public class PascalNumber {

public static void main(String[] args) {

System.out.println();
System.out.println(isPascal (6));
System.out.println(isPascal (15));
System.out.println(isPascal (7));

tatic int isPascal (int num) {


int pascalSum = 0;
int index = 0;
while(pascalSum < num){
pascalSum += index;
index++;
}
if(pascalSum == n)
return 1;
return 0;
}
}
1. Write a function fill with signature int[] fill(int[] arr, int k, int n) which does the following: It
returns an integer array arr2 of length n whose first k elements are the same as the first k elements
of arr, and whose remaining elements consist of repeating blocks of the first k elements. You
can assume array arr has at least k elements. The function should return null if either k or n is
not positive.

Examples: fill({1,2,3,5, 9, 12,-2,-1}, 3, 10) returns {1,2,3,1,2,3,1,2,3,1}. Fill({4, 2, -3, 12}, 1,


5) returns {4, 4, 4, 4, 4}. fill({2, 6, 9, 0, -3}, 0, 4) returns null.

import java.util.Arrays;
public class FillArray {

public static void main(String[] args) {


System.out.println(Arrays.toString(fill(new int[]{1,2,3,5,9,12,-2,-1}, 3,
10)));
System.out.println(Arrays.toString(fill(new int[]{4, 2, -3, 12}, 1, 5)));
System.out.println(Arrays.toString(fill(new int[]{2, 6, 9, 0, -3}, 0,
4)));

static int[] fill(int[] arr, int k, int n) {


if (k <= 0 || n <= 0)
return null;

int[] arr2 = new int[n];

for (int i = 0; i < n; ) {


for (int j = 0; j < k && i < n; j++) {
arr2[i] = arr[j];
i++;
}
}
return arr2;
}
}

2. Write a function sumIsPower with signatuare boolean sumIsPower(int[] arr)


which outputs true if the sum of the elements in the input array arr is a power of 2, false
otherwise. Recall that the powers of 2 are 1, 2, 4, 8, 16, and so on. In general a number is a
power of 2 if and only if it is of the form 2n for some nonnegative integer n. You may assume
(without verifying in your code) that all elements in the array are positive integers. If the input
array arr is null, the return value should be false.

Examples: sumIsPower({8,8,8,8}) is true since 8 + 8 + 8 + 8 = 32 = 2 5. sumIsPower({8,8,8})


is false, since 8+ 8 +8 = 24, not a power of 2.
public class SumPower {
static boolean sumIsPower(int[] arr) {
if (arr == null)
return false;
int sum = 0;
for(int num: arr) {
if(num <0)
return false;
sum += num;
}
int powerOf2 = 1;
while(powerOf2 < sum)
powerOf2 *= 2;
if(powerOf2 == sum)
return true;
return false;

}
public static void main(String[] args) {
System.out.println(sumIsPower(new int[]{8,8,16}));
System.out.println(sumIsPower(new int[]{2, 2, 2, 10}));
System.out.println(sumIsPower(new int[]{2, 6, 9, 0, 0}));

3. An array is said to be hollow if it contains 3 or more zeros in the middle that are preceded and
followed by the same number of non-zero elements. Write a function named isHollow that
accepts an integer array and returns 1 if it is a hollow array, otherwise it returns 0. The function
signature is int isHollow(int[ ] a).

Examples: isHollow({1,2,4,0,0,0,3,4,5}) returns true. isHollow ({1,2,0,0,0,3,4,5}) returns false.


: isHollow ({1,2,4,9, 0,0,0,3,4, 5}) returns false. isHollow ({1,2, 0,0, 3,4}) returns false.

public class HollowArray {

public static void main(String[] args) {


System.out.println(isHollow(new int[]{1, 2, 0, 0, 0, 3, 4}));
System.out.println(isHollow(new int[]{1,1,1,1,0,0,0,0,0,2,1, 2,18}));
System.out.println(isHollow(new int[]{1, 2, 0, 0, 3, 4}));
System.out.println(isHollow(new int[]{1,2,0, 0, 0, 3, 4, 5}));
System.out.println(isHollow(new int[]{3, 8, 3,0,0, 0, 3, 3}));
System.out.println(isHollow(new int[]{1, 2, 0,0,0, 3, 4, 0}));
System.out.println(isHollow(new int[]{0, 1, 2,0,0, 0, 3, 4}));
System.out.println(isHollow(new int[]{0, 0, 0}));
}
static int isHollow(int[] a) {
if (a.length < 3)
return 0;
int zeroCount = 0;

for (int i = 0, j = a.length - 1; i <= j; i++, j--) {


if ((a[i] == 0 && a[j] != 0) || (a[i] != 0 && a[j] == 0)){
return 0;
}
if (i == j && a[i] == 0) {
zeroCount++;
} else {
if (a[i] == 0)
zeroCount++;

if (a[j] == 0)
zeroCount++;
}
}

if (zeroCount >= 3) return 1;


return 0;
}
}

You might also like