Color Sort Problem

Given an array with n objects colored red, white or blue,
sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: Using library sort function is not allowed.

Example :

Input : [0 1 2 0 1 2]
Modify array so that it becomes : [0 0 1 1 2 2]

Solution

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: Chocolate in Box

Problem Statement:

Dexter and Debra are playing a game. They have N containers each having one or more chocolates. Containers are numbered from 1 to N, where ith container has A[i] number of chocolates.

The game goes like this. First player will choose a container and take one or more chocolates from it. Then, second player will choose a non-empty container and take one or more chocolates from it. And then they alternate turns. This process will continue, until one of the players is not able to take any chocolates (because no chocolates are left). One who is not able to take any chocolates loses the game. Note that player can choose only non-empty container.

The game between Dexter and Debra has just started, and Dexter has got the first Chance. He wants to know the number of ways to make a first move such that under optimal play, the first player always wins.

Input Format
The first line contains an integer N, i.e., number of containers.
The second line contains N integers, i.e., number of chocolates in each of the containers separated by a single space.

Output Format
Print the number of ways to make the first move such that under optimal play, the first player always wins. If the first player cannot win under optimal play, print 0.

Constraints
1 ≤ N ≤ 106
1 ≤ A[i] ≤ 109

Sample Input

2
2 3

Sample Output

1

Explanation

Only 1 set of moves helps player 1 win.

Player:      1      2      1      2      1
Chocolates: 2 3 -> 2 2 -> 1 2 -> 1 1 -> 0 1

Sample Data

Output:

321143

Theory Data for the solution and algorithm

Finding loop in a singly linked-list

You can detect it by simply running two pointers through the list.
Start the first pointer p1 on the first node and the second pointer p2 on the second node.

Advance the first pointer by one every time through the loop, advance the second pointer by two. If there is a loop, they will eventually point to the same node. If there’s no loop, you’ll eventually hit the end with the advance-by-two pointer.

Consider the following loop:

head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8
                  ^                        |
                  |                        |
                  +------------------------+

Starting A at 1 and B at 2, they take on the following values:

p1   p2
=    =
1    2
2    4
3    6
4    8
5    4
6    6

Because they’re equal, and P2 should always be beyond p1 in a non-looping list (because it’s advancing by two as opposed to the advance-by-one behavior of p1), it means you’ve discovered a loop.

The pseudo-code will go something like this:

  • Start with hn(Head Node )of the linked list
  • If hn==null; return false; //empty list
  • if hn.next!=null
    • p1=hn; p2=hn;
    • While p2!=null loop
      • p1=p1.next//Advancing p1 by 1
      • if p2.next!=null
        • p2=p2.next.next//Advancing p2 by 2
        • else return false
      • if p1==p2
        • return true// Loop was found
    • return false// till now no loop was found

Once you know a node within the loop, there’s an O(n) guaranteed method to find the start of the loop.

Let’s return to the original position after you’ve found an element somewhere in the loop but you’re not sure where the start of the loop is.

                                 p1,p2 (this is where p1 and p2
                                 |               first met).
                                 v
head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8
                  ^                        |
                  |                        |
                  +------------------------+

This is the process to follow:

  • First, advance p2 and set the loopsize to 1.
  • Second, while p1 and p2 are not equal, continue to advance p2, increasing the loopsize each time. That gives the size of the loop, six in this case.
    If the loopsize ends up as 1, you know that you must already be at the start of the loop, so simply return A as the start, and skip the rest of the steps below.
  • Third, simply set both p1 and p2 to the first element then advance p2 exactly loopsize times (to the 7 in this case). This gives two pointers that are different by the size of the loop.
  • Lastly, while p1 and p2 are not equal, you advance them together. Since they remain exactly loopsize elements apart from each other at all times, p1 will enter the loop at exactly the same time as p2 returns to the start of the loop. You can see that with the following walk through:
    • loopsize is evaluated as 6
    • set both p1 and p2 to 1
    • advance p2 by loopsize elements to 7
    • 1 and 7 aren’t equal so advance both
    • 2 and 8 aren’t equal so advance both
    • 3 and 3 are equal so that is your loop start

Now, since each those operations are O(n) and performed sequentially, the whole thing is O(n).

Source

Algorithm Name: Floyd–Warshall algorithm

Common Mistakes in Collections

Source : http://javabeanz.wordpress.com/2007/07/13/treemap-vs-hashmap/

Classes like Integer, String, Double etc implements Comparable interface. So if we are to use an object of a custom class as the key, ensure that it’ s class implements the Comparable interface.

public class MyCustomKey implements Comparable
{
    private int value;
    public MyCustomKey(int value)
    {
       this.value = value;
    }           

    public int compareTo (MyCustomKey key)
    {
       int comparison = 0;           

       // Note:
       // Return -1 if this.value < key.value
       // Return  0 if this.value = key.value
       // Return  1 if this.value > key.value           

       return (comparison);
    }
}

A common mistake that everyone does is not to override the hashcode(). If we are failing to do so, map.get(new MyCustomKey()); may not give you what you were expecting. So it is always advised to override the hashCode() if objects of that class is being used as a key.

public class MyCustomKey implements Comparable
{
    private int value;
    public MyCustomKey(int value)
    {}
    public int compareTo (MyCustomKey key)
    {}        

    public int hashCode()
    {
        // Note:
        // If two objects are equal then their corresponding hashCode ()
        // should return the same value too.
        return (this.value * 199);
    }
}

When you are using your custom object as a key to a HashMap, make sure you do the following

1) implement Comparable
2) override compareTo method, and give its implementation
3) override hashCode and equals method, and give their implementation.
4) Always, make your key object as immutable, so that it is not changed after you add it to a HashMap as key.