Collections of Java Question and Answers
Collections of Java Question and Answers
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
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;
return isItPrime;
}
}
if (isItPrime)
{
System.out.println(inputNumber+" is a prime number.");
}
else
{
System.out.println(inputNumber+" is not a prime
number.");
}
sc.close();
}
}
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,
import java.util.Scanner;
Output:
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;
}
}
package prime;
• 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;
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.
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.
//Lets take two numbers 55 and 121 and find their GCD
int num1 = 55, num2 = 121, gcd = 1;
}
Output:
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.
Output:
import java.util.Scanner;
public class GCDExample3 {
}
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:
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.
Note in our implementation that we'll use modulo instead of subtraction since it's basically many
subtractions at a time:
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.
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:
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;
}
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.
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).
✓ 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 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.
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.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):
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.
@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.
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:
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.
@Test
public void testGCD() {
Assert.assertEquals(6, EuclideanAlgorithm.gcd(12, 18));
}
@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.
To understand this example, you should have the knowledge of the following Java programming topics:
The LCM of two integers is the smallest positive integer that is perfectly divisible by both the numbers
(without a remainder).
// 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
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.
We can also use GCD to find the LCM of two numbers using the following formula:
If you don't know how to calculate GCD in Java, check Java Program to find GCD of two numbers.
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.
package com.beginnersbook;
import java.util.Scanner;
public class JavaExample {
static int fact(int num) {
int factorial;
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();
}
}
}
Each number is the sum of the two numbers directly above it.
package com.JournalDev;
import java.util.Scanner;
System.out.println();
}
}
}
The code inputs the number of rows of pascal triangle from the user.
Code Breakdown
The outer most for loop is responsible for printing each row. It will run ‘row’ number of times.
The next for loop is responsible for printing the spaces at the beginning of each line.
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.
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.
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)
1 3 3 1
You should do this for row munger 4 and 5 as well to understand how the formula works.
Output
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
Example
public class PascalsTriangle {
static int factorial(int n) {
int f;
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.
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.
Solution:
We have to find the entry of the 4th row's 4th term. Here, n=4 and r=4.
Solution:
We have to find the entry of 6th row's 5th term. Here, n=6 and r=5.
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.
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.
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 {
//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);
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'.
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{
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 :
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.
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 :
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.
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
*/
/*
* 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;
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
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.
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.
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 {
/**
* 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.
import java.util.Scanner;
/**
* How to check if String is palindrome in Java
* using StringBuffer and for loop.
*
* @author java67
*/
reader.close();
}
return input.equals(reverseOfString);
}
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.
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.
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 {
}
/*
* 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());
return sb.toString().trim();
}
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.
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.
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.
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 {
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.
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
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.
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.
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 {
/*
* 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.
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.
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 {
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.
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.
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.
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.
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²)
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.
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 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) {
// 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
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]
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.
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.
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{
/*
* 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);
}
}
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.
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.
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.
a = Integer.MAX_VALUE;
b = 10;
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 :-)
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.
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 {
// another example
a = Integer.MIN_VALUE;
b = Integer.MAX_VALUE;
a = (a + b) - (b = a);
int x = 30;
int y = 60;
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.
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.
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 :
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 using iteration and recursion
*
* @author WINDOWS 8
*
*/
public class FactorialTest {
/**
* 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.
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.
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:
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:
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 {
/*
* 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.
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.
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.
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);
}
}
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
*/
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.
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.
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.
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 {
}
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.
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.
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.
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
*/
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
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 :
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 .
/**
* 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;
}
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.
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.
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 {
/*
* 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 :
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.
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.
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 {
/*
* 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) {
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.
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.
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{
/**
* @return largest prime factor of a number
*/
public static int largestPrimeFactor(long number) {
int i;
long copyOfInput = number;
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 :
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.
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 :
}
/*
* 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
*/
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.
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.
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.
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 {
while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}
if(length%2 == 1){
middle = middle.next();
}
class LinkedList{
private Node head;
private Node tail;
public LinkedList(){
this.head = new Node("head");
tail = head;
}
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.
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.
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.
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.
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.
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.
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;
}
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);
for(char ch : characters){
int index = sbSecond.indexOf("" + ch);
if(index != -1){
sbSecond.deleteCharAt(index);
}else{
return false;
}
}
/**
* 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.
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.
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 {
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
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.
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.
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.
import java.util.Arrays;
/**
* Java program to find top two maximum numbers from an integer
array.
*
* @author http://java67.blogspot.com
*/
public class TopTwoMaximum{
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.
data.txt
A computer program is a collection of instructions that performs specific task when executed by a
computer.
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;
words.add(s);
count = 1;
if(words.get(i).equals(words.get(j))){
count++;
//If maxCount is less than count then store value of count in maxCount
maxCount = count;
word = words.get(i);
br.close();
}
Output:
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.
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.
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 {
/*
* 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) {
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.
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.
• 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
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.
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.
// Calculate n value
//(we add 1 because one element is already missed)
int n = input.length + 1;
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
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.*;
// Calculate n value
int n = hsobj.size() + 1;
Output :
Missing number in an array is : 8
Output :
Missing numbers in an array are : 3 4 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.*;
return max;
}
}
Output :
Missing numbers in an array are : 2 4 5 7
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 :
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.
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 :
import java.util.Arrays;
/**
* Java Program to find pairs on integer array whose sum is equal to k
*
* @author WINDOWS 8
*/
public class ProblemInArray{
/**
* 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) {
}
}
/**
* 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 {
/**
* 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);
/*
* 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 {
/**
* 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);
/*
* 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.
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.
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.
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.
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*
* 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.
To find union of two sorted arrays, follow the following merge procedure :
return 0;
}
Output:
1 2 3 4 5 6 7
int ans = 0;
if (m > n) {
ans = m;
}
else
ans = n;
UnionArray(arr1, arr2);
}
}
// Function calling
printIntersection(arr1, arr2, m, n);
return 0;
}
Output:
2 5
Examples:
// 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);
}
}
Output:
1 7
7 1
5 3
4 4
Examples :
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.
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.
class GFG
{
int a = 0, b = 0;
else
b++;
}
// Driver Code
public static void main(String[] args)
{
// Input given array A
int A[] = {1, 2, 11, 5};
// 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).
Examples:
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.
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.
import java.util.*;
class Main
{
// 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
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;
if (start == -1) {
System.out.println("Key not present in array");
return;
}
// 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
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
Output: {3,2,5}
Output: {7}
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?)
• What would be the time and space complexity of removing duplicates from n size array?
• How can we improve the time complexity?
Solution Steps
Pseudo-Code
bool binary_search(int B[], int n, int K)
{
int low = 0, high = n
if( B[mid] == K )
return True
else
low = mid + 1
}
return false
}
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).
• 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.
Examples:
Input: {2, 3, 7, 6, 8, -1, -10, 15}
Output: 1
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.
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.
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.
class GFG {
val = arr[i];
// Driver code
public static void main (String[] args)
{
int arr[] = { 2, 3, 7, 6, 8, -1, -10, 15 };
int arr_size = arr.length;
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.
Output :
Examples:
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.
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;
}
// 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]);
return 0;
}
Output:
Indices in array 1 : 0, 1, 2
Indices in array 2 : 0
Example :
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).
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.
res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4
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.
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] + " ");
}
}
}
Output :
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;
Output :
Repeating elements are 4 2
Examples:
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);
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.
// Driver code
public static void main(String[] args)
{
int arr[] = {2, 3, -4, -1, 6, -9};
int n = arr.length;
rearrange(arr, n);
Output:
Given array is
2 3 -4 -1 6 -9
Rearranged array is
-1 3 -4 2 -9 6
Examples:
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;
return j;
}
n = removeDuplicates(arr, n);
Output:
1 2 3 4 5
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;
arr[j++] = arr[n-1];
return j;
}
n = removeDuplicates(arr, n);
Output:
1 2 3 4 5
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
int j = 0;
int i = 1;
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}.
Kadane’s Algorithm:
Initialize:
max_so_far = 0
max_ending_here = 0
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
max_so_far = max_ending_here = 0
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));
}
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.
}
return max_so_far;
}
Following is another simple implementation suggested by Mohit Kumar. The implementation handles
the case when all numbers in array are negative.
Output:
Maximum contiguous sum is 7
To print the subarray with the maximum sum, we maintain indices whenever we get the maximum sum.
// 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);
}
}
Output:
Maximum contiguous sum is 7
Starting index 2
Ending index 6
Examples:
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.
class GFG {
/* Returns the product of max product subarray.*/
static int maxSubarrayProduct(int arr[])
{
// Initializing result
int result = arr[0];
int n = arr.length;
// 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));
}
}
Output:
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.
class ProductSubarray {
// Driver Code
public static void main(String[] args)
{
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.
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 {
/*
* 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 :
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
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.
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.
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
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 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 {
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)
{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.
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.
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
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.
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.
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 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
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
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
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.
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.
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!.
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.
Examples (note: your program must work for all values of a and n, not just
those given here!)
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.
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.
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
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);
}
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
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.
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:
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.
/**
* Created by sachinkeshav on 12/30/14.
*/
public class NonZeroArray {
return 1;
}
}
public class ComputeDepth {
if (!flags[rem]) {
flags[rem] = true;
}
}
if (finalFlag) break;
index++;
}
return index;
}
}
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.)
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)
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;
if(matches == 0)
break;
}
return matches;
}
}
public class PatternMatcher {
/**
* Created by sachinkeshav on 12/31/14.
*/
public class StackedNumber {
if (sum > n)
return 0;
index++;
sum += index;
}
}
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.
int sum = 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.
long square = n * n;
long cube = n * n * n;
while (cube > 0) {
long cubeDigit = cube % 10;
cube /= 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.
if (digit != remainder)
return 0;
anA /= 10;
}
}
return 1;
}
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 {
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.
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.
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 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 {
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.
You may assume that such a number is computable on a 32 bit machine, i.e, you do not have to detect integer
package com.knight.exam.java.smallestNDigit;
/**
* Created by sachinkeshav on 1/2/15.
*/
public class SmallestNDigit {
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.
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
int numClusters = 1;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] != a[i + 1]) {
numClusters++;
}
}
if (numClusters == 1) {
result[0] = a[0];
return result;
}
int clusterIndex = 0;
return result;
}
}
3. Define an array to be a railroad-tie array if the following three conditions hold
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 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)
}
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
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
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
int count = 0;
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.
Hint: Make sure that your solution handles all the above examples correctly!
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)
{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 {
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
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
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)
Examples
import java.util.Arrays;
public class BinaryRepresentation {
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;
}
}
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
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:
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.
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.
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 {
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:
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 {
int size = 0;
int nCopy = n;
for (int i = 2; i <= nCopy; ) {
if (isPrime(i) && nCopy % i == 0) {
size++;
nCopy /= i;
} else i++;
}
return result;
}
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:
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.
else {
k++;
if (a[i] == pattern[k])
matches++;
else return 0;
}
}
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.
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
import java.util.Arrays;
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
int nCopy = n;
int sum = 0;
while (nCopy > 0) {
int digit = nCopy % 10;
nCopy /= 10;
int product = 1;
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)
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
int position = 0;
for (int i = a.length - 1; i > 0; i--) {
int digit = 0;
position++;
}
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
{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.
int count = 0;
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)
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 {
position++;
}
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
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 {
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 {
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;
{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}
return 1;
}
}
if (sum == n) return 1;
else return 0;
}
return 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
because 6 - 2 == 4
{1, 2, 1, 2, 1, 4, 1, 6, 4} 4
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.
if (number == n) return 1;
return 0;
}
return 0;
}
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
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.
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!
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)
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.
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;
}
}
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
return 1;
}
}
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;
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 {
int hour = 0;
int minute = 0;
int second = 0;
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
Hint: Make sure that your solution does not exceed the boundaries of the array!
public class MartianArray {
if (a[i] == 1)
countOf1++;
if (a[i] == 2)
countOf2++;
}
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
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;
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)
{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 {
If you are programming in Java or C#, the function signature is int is121Array(int[ ] a)
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!
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;
}
}
}
If you are writing in Java or C#, the function signature is int[ ] pairwiseSum(int[ ] a)
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;
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!
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 {
int square = 0;
int number = 1;
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
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}));
}
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])
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
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.
if (a.length < n)
return 0;
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)
if (n1 == n2)
return 1;
int countOfFactor1 = 0;
int countOfFactor2 = 0;
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)
Copy and paste your answer here and click the "Submit answer" button
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)
int count = 1;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1])
return 0;
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 {
System.out.println(Arrays.toString(d));
}
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:
Copy and paste your answer here and click the "Submit answer" button
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;
if (a[j] == 0)
zeroCount++;
}
}
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
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:
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
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.
Hint use modulo base 10 arithmetic and integer division to get the digits of an integer.
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.
}
}
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
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 {
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 {
if (a[a.length - 1 - i] % 2 == 0) tailCount++;
if (oddFlag) return 1;
else return 0;
}
// this is best
static int isDaphne(int[] a) {
boolean oddFlag = false;
return 1;
}
static int isDaphne0(int[] a) {
boolean evenFlag = false;
boolean oddFlag = false;
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);
if (factor % 2 != 0)
return 0;
}
return 1;
}
}
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.
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;
}
}
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.
int sum = 0;
while (n > 0) {
int digit = n % 10;
n /= 10;
sum += digit;
}
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)
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.
int primeSum = 0;
If you are writing in Java or C#, the function signature is int isComplete (int[ ] a)
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}));
}
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.
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.
if (primeProduct)
return 1;
return 0;
}
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.
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).
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)
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 {
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).
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.
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 {
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}));
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.
Hint: Use modulo base 10 and integer arithmetic to isolate the digits of the number.
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}));
}
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.
}
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.
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)
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}));
}
if (isPrime(anA) == 1)
primeFlag = true;
}
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.
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
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 {
if (isPrime(a1 + 2) && a2 == a1 + 2) {
twinPrimeFlag = true;
break;
}
}
}
if (!twinPrimeFlag)
return 0;
}
return 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 {
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.
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)
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;
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}));
}
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)
if (n < 0 || m < 0)
return 0;
int factorsOfN = 2;
int factorsOfM = 2;
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.
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 {
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.
int fibonacci = 0;
int fibo1 = 1;
int fibo2 = 1;
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.
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}));
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.
}
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)
int fancyNumber = 0;
int fancy1 = 1;
int fancy2 = 1;
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;
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.
int prevNum = 1;
int num = 0;
return 0;
}
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 {
System.out.println();
}
if (count != 2) {
return 0;
}
}
return 1;
}
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.
/**
* Created by sachinkeshav on 1/2/15.
*/
public class OddHeavy {
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.
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.
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}));
}
1. Write a function named factorTwoCount that returns the number of times that 2 divides
the argument.
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.
if (a[a.length - 1 - i] % 2 == 0) tailCount++;
// this is best
static int isDaphne(int[] a) {
boolean oddFlag = false;
3. Write a function called goodSpread that returns 1 if no value in its array argument occurs
more than 3 times in the array.
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 {
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)
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.
return 1;
}
There are three questions on this test. You have two hours to complete it.
Please do your own work.
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)
You do **not** have to write this function! You just have to call it.
public class BeanArray {
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.
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)
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 21=1, 42=2, 74=3, 117=4, 1611=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
int prevNum = 1;
int num = 0;
return 0;
}
static int isBunker(int n) {
int previousElement = 1;
int index = 0;
int element = 0;
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)
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)
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}));
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)
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 {
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}));
}
if (isPrime(anA) == 1)
primeFlag = true;
}
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)
System.out.println();
System.out.println(isPascal (6));
System.out.println(isPascal (15));
System.out.println(isPascal (7));
import java.util.Arrays;
public class FillArray {
}
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).
if (a[j] == 0)
zeroCount++;
}
}