GCD algorithm in Java

Given 2 non negative integers m and n, find gcd(m, n)

GCD of 2 integers m and n is defined as the greatest integer g such that g is a divisor of both m and n.
Both m and n fit in a 32 bit signed integer.

Example

m : 6
n : 9

GCD(m, n) : 3

NOTE : DO NOT USE LIBRARY FUNCTIONS

HackerRank: Find Single Integer out of an Array

Problem Statement

Given an array of integers, every element appears twice except for one. Find that single one.

Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example :

Input : [1 2 2 3 1]
Output : 3

Solution

Logic:

The basic logic that A XOR A = 0 means that means all the doubles will be XOR’ed out to 0 and the remaining number will be the result of the XOR.

HackerRank: Sherlock and The Beast

Problem Statement

Sherlock Holmes suspects his archenemy, Professor Moriarty, is once again plotting something diabolical. Sherlock’s companion, Dr. Watson, suggests Moriarty may be responsible for MI6’s recent issues with their supercomputer, The Beast.

Shortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting The Beastwith a virus; however, he also gives him a clue—a number, NN. Sherlock determines the key to removing the virus is to find the largest Decent Number having NN digits.

A Decent Number has the following properties:

  1. Its digits can only be 3‘s and/or 5‘s.
  2. The number of 3‘s it contains is divisible by 5.
  3. The number of 5‘s it contains is divisible by 3.
  4. If there are more than one such number, we pick the largest one.

Moriarty’s virus shows a clock counting down to The Beast‘s destruction, and time is running out fast. Your task is to help Sherlock find the key before The Beast is destroyed!

Constraints
1T201≤T≤20
1N1000001≤N≤100000

Input Format

The first line is an integer, TT, denoting the number of test cases.

The TT subsequent lines each contain an integer, NN, detailing the number of digits in the number.

Output Format

Print the largest Decent Number having NN digits; if no such number exists, tell Sherlock by printing -1.

Sample Input

4
1
3
5
11

Sample Output

-1
555
33333
55555533333

Explanation

For N=1, there is no decent number having 1 digit (so we print 1−1).
For N=3, 555 is the only possible number. The number 5 appears three times in this number, so our count of 5‘s is evenly divisible by 3 (Decent Number Property 3).
For N=5, 33333 is the only possible number. The number 3 appears five times in this number, so our count of 3‘s is evenly divisible by 5 (Decent Number Property 2).
For N=11, 55555533333 and all permutations of these digits are valid numbers; among them, the given number is the largest one.

Solution:

HackerRank: DynamicArray

Problem Statement

There are N sequences. All of them are initially empty, and you are given a variable lastans = 0. You are given Q queries of two different types:

  • 1 x y” – Insert y at the end of the ((x XOR lastans) mod N)th sequence.
  • 2 x y” – Print the value of the (y mod size)th element of the ((x XOR lastans) mod N)th sequence. Here, $size$ denotes the size of the related sequence. Then, assign this integer to lastans.

Note: You may assume that, for the second type of query, the related sequence will not be an empty sequence. Sequences and the elements of each sequence are indexed by zero-based numbering.

You can get more information about XOR from Wikipedia. It is defined as ^ in most of the modern programming languages.

Input Format

The first line consists of $N$, number of sequences, and $Q$, number of queries, separated by a space. The following $Q$ lines contains one of the query types described above.

Constraints
1 < N,Q < 10^5
0 < x < 10^9
0 < y < 10^9

Output Format

For each query of type two, print the answer on a new line.

Sample Input

2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1

Sample Output

7
3

Explanation

The first sequence is 5, 3 and the second sequence is 7.

Solution:

2D Array: Hour Glass problem solution

Problem Statement:

You are given a 2D array with dimensions 6*6. An hourglass in an array is defined as a portion shaped like this:

a b c
  d
e f g

For example, if we create an hourglass using the number 1 within an array full of zeros, it may look like this:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

Actually, there are many hourglasses in the array above. The three topmost hourglasses are the following:

1 1 1     1 1 0     1 0 0
  1         0         0
1 1 1     1 1 0     1 0 0

The sum of an hourglass is the sum of all the numbers within it. The sum for the hourglasses above are 7, 4, and 2, respectively.

In this problem, you have to print the largest sum among all the hourglasses in the array.

Note: If you have already solved the problem “Java 2D array” in the data structures chapter of the Java domain, you may skip this challenge.

Input Format

There will be exactly 6 lines of input, each containing 6 integers separated by spaces. Each integer will be between -9 and 9, inclusively.

Output Format

Print the answer to this problem on a single line.

Sample Input

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

Sample Output

19

Explanation

The hourglass possessing the largest sum is:

2 4 4
  2
1 2 4

Solution:

HackerRank: Sparse Arrays

Problem Statement

There are N strings. Each string’s length is no more than 2020 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.

Input Format

The first line contains N, the number of strings.
The next N lines each contain a string.
The N+2nd line contains Q, the number of queries.
The following Q lines each contain a query string.

Constraints

1N1000
1Q1000
1lengtof anstring20

Sample Input

4
aba
baba
aba
xzxb
3
aba
xzxb
ab

Sample Output

2
1
0

Explanation

Here, “aba” occurs twice, in the first and third string. The string “xzxb” occurs once in the fourth string, and “ab” does not occur at all.

Solution

Combinations of a String

Problem:
Write an algorithm to print all possible combinations of characters in a string.

Solution:
Since we need to generate combinations, we can start with a single character and then continue to add a character to combinations we have seen so far.

Let’s use “XYZ” as an example.

public void buildTree(String input, StringBuffer output, int k)
{
    for (int i = k; i < input.length(); i++)
    {
        output.append(input.charAt(i));
        buildTree(input, output, i + 1);
        output.deleteCharAt(output.length() - 1);
    }
} 

public static void main(String[] args){
     buildTree("XYZ", new StringBuffer(), 0);
}

Dry Run just to give an idea:

X–>Y–>Z
–>Z–>Y

Y–>X–>Z
–>Z–>X

Z–>Y–>X
–>X–>Y

Gold for 7 Days of Work Puzzle

Problem Statement:

You’ve got someone working for you for seven days and a gold bar to pay them. You must pay the worker for their work at the end of every day. If you are only allowed to make two breaks in the gold bar, how do you pay your worker?
(Assuming equal amount of work is done during each day thus requiring equal amount of pay for each day)

Answer

The trick is not to try and how to cut in such a way to make 7 equal pieces but rather to make transactions with the worker. Make two cuts on the gold bar such that you have the following sizes of bars.

1/7, 2/7 and 4/7.

Day Pay Take Back Total Paid Amount Balance Amount
1 1/7 N/A 1/7 2/7, 4/7
2 2/7 1/7 2/7 1/7, 4/7
3 1/7 N/A 3/7 4/7
4 4/7 1/7, 2/7 4/7 2/7, 1/7
5 1/7 N/A 5/7 2/7
6 2/7 1/7 6/7 1/7
7 1/7 N/A 7/7 N/A

Fastest 3 out of 25 Horses Problem

Problem Statement

You have 25 horses, and you want to pick the fastest 3 horses out of those 25. Each race can have maximum of 5 horses at the same time. What is the minimum number of races required to find the 3 fastest horses without using a stopwatch?

Solution

Let’s say that we have 5 races of 5 horses each, so each row in the table above represents a race.

H1 H2 H3 H4 H5
H6 H7 H8 H9 H10
H11 H12 H13 H14 H15
H16 H17 H18 H19 H20
H21 H22 H23 H24 H25

Let each row represent a race.

Step 1: Perform 5 races of each set.

Result:

1st 2nd 3rd 4th 5th
H1 H2 H3 H4 H5
H6 H7 H8 H9 H10
H11 H12 H13 H14 H15
H16 H17 H18 H19 H20
H21 H22 H23 H24 H25

Step 2: Elimination by logical analysis:

  • We can eliminate the slowest 2 horses in each group since those horses are definitely not in the top 3
  • The 5 group leaders are not necessarily the 5 fastest horses, therefore race those 5 horses against each other (H1, H6, H11, H16, and H21) {Race 6}, Let’s say that the 3 fastest in that group are H1, H6, and H11 – automatically we can eliminate H16 and H21 since those 2 are definitely not in the top 3
  • We can automatically eliminate all the horses that H16 and H21 competed against in the preliminary races as they were slower than H16 and H21
  • We also know that H1 is the fastest horse in the group since he was the fastest horse out of the 5 group leaders
  • if H6 and H11 are the 2nd and 3rd fastest in the group leaders, then we should be able to eliminate H8 since H6 raced against him and he was in 3rd place in that race
  • We can also eliminate H12 and H13 since H11 was the 3rd fastest in the group leaders, and H12 and H13 were slower than H11
  • This leaves us with the following horses to determine the 2nd and 3rd fastest horses:
H2 H3 H6 H7 H11

Race the last Set {Race 7} to get the Top 2nd and 3rd racers with H1 as the fastest.

Total number of Races: 7

100 floors with 2 eggs puzzle

Problem Statement:

There is a building of 100 floors  If an egg drops from the Nth floor or above it will break. If it’s dropped from any floor below, it will not break. You’re given 2 eggs.

Give an Algorithm to find N, while minimizing the number of drops for the worst case.

Solution:

The Problem comes with a general equation as X(Max Number of floors) = n*n;

So in this case for example, X= 100 Floors( => n=10)

now use the value n to traverse. This means that drop the first egg from 10th floor, then 20th floor, then 30th and so on up to 90.

The floor from which it breaks, say 60th, then go back 10 floors and try each floor to find N.

After Floor 90, Start moving 1 by 1.

Worst case scenario:

eggs break at 99th floor.

Egg drops: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80 -> 90 -> 91 -> 92 -> 93 -> 94 -> 95 -> 96 -> 97 -> 98 -> 99

Max Attempts: 18