Popular Posts

Tuesday, February 21, 2012

Java race condition

A race condition or race hazard is a flaw in an electronic system or process whereby the output or result of the process is unexpectedly and critically dependent on the sequence or timing of other events. The term originates with the idea of two signals racing each other to influence the output first.

http://www.cs.usfca.edu/~parrt/course/601/lectures/threads.html
http://java.sun.com/developer/Books/performance2/chap3.pdf

All about interviews..........

    Saturday, February 18, 2012

    Length of the longest substring without repeating characters

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA” and “DEFGAB”, with length 6.
    public class LongestSubString {

    public static void main(String[] args) {
    String str
    = "ABDEFGABEF";

    // Used for tracking the position of last occurrence of character in the
    // string.
    int[] chars = new int[256];
    for (int i = 0; i < 256; i++) {
    chars
    [i] = -1;
    }

    int maxLength = 1;
    int currentLength = 1;

    for (int i = 0; i < str.length(); i++) {
    int lastOccrrenceIndex = chars[str.charAt(i)];
    if (lastOccrrenceIndex == -1
    || (i - currentLength > lastOccrrenceIndex)) {
    currentLength
    ++;
    } else {
    if (currentLength > maxLength)
    maxLength
    = currentLength;
    currentLength
    = i - lastOccrrenceIndex;
    }
    chars
    [str.charAt(i)] = i;
    }
    if (currentLength > maxLength)
    maxLength
    = currentLength;
    System
    .out.println(maxLength);
    }
    }


    Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26.
    Auxiliary Space: O(d)

    Refer : http://www.geeksforgeeks.org/archives/15859

    Matrix Chain Multiplication

    Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain.
    Refer : http://www.geeksforgeeks.org/archives/15553

    Binomial Coefficient

    Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k).
    The value of C(n, k) can recursively calculated using following standard formula for Binomial Cofficients.

       C(n, k) = C(n-1, k-1) + C(n-1, k)
       C(n, 0) = C(n, n) = 1

    Refer : http://www.geeksforgeeks.org/archives/17806

    Friday, February 17, 2012

    N Queen Problem

    The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.
    Refer : http://www.geeksforgeeks.org/archives/13387

    Rat in a Maze

    A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down.
    In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with limited number of moves.

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

    int[][] maze = {
    { 1, 0, 0, 0 },
    { 1, 1, 0, 1 },
    { 0, 1, 0, 0 },
    { 1, 1, 1, 1 }
    };

    int m = maze.length;
    int n = maze[0].length;
    int[][] solution = new int[m][n];

    boolean isSolutionAvailable = getSolution(maze, solution, 0, 0);
    if (isSolutionAvailable) {
    printMatrix(solution);
    } else {
    System.out.println("Solution is not available");
    }
    }

    private static void printMatrix(int[][] a) {
    System.out.println();
    for (int i = 0; i < a.length; i++) {
    for (int j = 0; j < a[0].length; j++) {
    System.out.print(" " + a[i][j] + " ");
    }
    System.out.println();
    }
    }

    private static boolean getSolution(int[][] maze, int[][] solution, int i,
    int j) {
    int m = maze.length;
    int n = maze[0].length;

    if (i < 0 || i >= m || j < 0 || j >= n || maze[i][j] == 0) {//check if path is blocked
    return false;
    }

    if (i == m - 1 && j == n - 1) {
    solution[i][j] = 1;
    return true;
    }

    // At each position look in forward and downward direction.
    if (getSolution(maze, solution, i, j + 1)
    || getSolution(maze, solution, i + 1, j)) {
    solution[i][j] = 1;
    return true;
    }
    return false;
    }
    }

    Refer : http://www.geeksforgeeks.org/archives/13376

    The Knight’s tour problem

    Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems which are typically solved using backtracking technique have following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for these problems is to try all configurations and output a configuration that follows given problem constraints. Backtracking works in incremental way and is an optimization over the Naive solution.

    For example, consider the following Knight’s Tour problem.
    The knight is placed on the empty board and, moving according to the rules of chess, must visit each square exactly once.

    Refer : http://www.geeksforgeeks.org/archives/12916

    Thursday, February 16, 2012

    Cuboidal boxes

    You are given a lot of cuboid boxes with different length, breadth and height. You need to find the maximum subset which can fit into each other.
    For example:
    If Box A has LBH as 7 8 9
    If Box B has LBH as 5 6 8
    If Box C has LBH as 5 8 7
    If Box D has LBH as 4 4 4
    then answer is A,B,D
    A box can fit into another only and only if all dimensions of that is
    less than the bigger box. Also Rotation of boxes is not possible.
    Answer:
    I think this is a modification of longest increasing subsequence problem . First , sort by length then find the longest increasing subsequence by width. Now, in this solution find longest increasing subsequence by height . This would be the answer to this question.

    Second non repeating character

    For a given a string, find its second non-repeating character.
    public class SecondNonRepeatingCharacter {
    /**
    * Prints second non repeating character. O(N) time complexity O(1) space
    * complexity
    *
    * @param args
    */
    public static void main(String[] args) {
    String str = "nonrepeatingcharacter";
    // in the above string first non repeating character is o
    // second one is p

    // create an array to store char count
    int[] charCount = new int[26];

    // scan the string and store each character count.
    for (int i = 0; i < str.length(); i++) {
    charCount[str.charAt(i) - 'a']++;
    }

    int nonRepeatingCharcter = 0;
    for (int i = 0; i < str.length(); i++) {
    int index = str.charAt(i) - 'a';
    if (charCount[index] == 1) {
    nonRepeatingCharcter++;
    if (nonRepeatingCharcter == 2) {
    System.out.println("Secondnon repeating character : "
    + str.charAt(i));
    break;
    }
    }
    }

    // prints how many times each character is repeated.duplicates are
    // allowed
    // for (int i = 0; i < str.length(); i++) {
    // int index = str.charAt(i) - 'a';
    // if (charCount[index] > 0)
    // System.out.println("char : " + str.charAt(i) + " repeated : "
    // + charCount[index] + " times.");
    // }

    }
    }

    Coin change

    Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.

    For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5.

    Refer : http://www.geeksforgeeks.org/archives/17401

    Find a number which equals to the index

    Given an array of positive and negative numbers sorted in ascending order.Find a number which is equal to the index of that number in array.
    ex: Array = {-3,-1,0,1,4}
    ans: a[4]=4
    We can do it by linear search in O(n) time or by doing binary search in O(logN) time.

    public class FixedPoint {
    public static void main(String[] args) {
    int[] a = { -10, -5, 0, 3, 7 };
    int fixedPoint = getFixedPointNumber(a, 0, a.length - 1);

    if (fixedPoint != -1) {
    System.out.println("Number is : " + fixedPoint);
    } else {
    System.out.println("There is Number satisying the condition.");
    }
    }

    /**
    * Returns a number a[i] which satisfies the condition a[i]=i
    *
    * @param a
    * @param low
    * @param high
    * @return
    */
    private static int getFixedPointNumber(int[] a, int low, int high) {

    if (a == null || a.length == 0 || low < 0 || high >= a.length
    || low > high)
    return -1;

    int mid = (low + high) / 2;

    if (a[mid] == mid) {
    return mid;
    } else if (a[mid] < mid) {
    return getFixedPointNumber(a, mid + 1, high);
    } else {
    return getFixedPointNumber(a, low, mid - 1);
    }
    }

    }

    Children in a country

    In a country in which people only want boys every family continues to have children until they have a boy. If they have a girl, they have another child. If they have a boy, they stop. What is the proportion of boys to girls in the country?

    Ans:
    The possibile sequence and the respective probabilty of new born can be:
    B - 1/2
    GB - 1/2*1/2
    GGB - 1/2*1/2*1/2
    GGGB - 1/2*1/2*1/2*1/2
    ...
    ...
    After Summing it up. Total Number of Boys is: 1/2 + 1/2*1/2 + 1/2*1/2*1/2 + ... = 1 On the same lines, Total number of Girls is: 0 + 1/2*1/2 + 2 * 1/2*1/2*1/2 + 3 * 1/2*1/2*1/2 + ... Which also, give 1 on summing up.
    Answer is 50/50

    Wednesday, February 15, 2012

    Nth prime number

    Created an array to hold all the discovered primes. For a given a number, check if it already is in the list or not. If yes, it is a prime. If not, check if any of the primes in the list, less than square root of the number, is a factor of this number or not.
                 The solution proposed by the Project Euler authors improvised on this. They used an additional fact that any prime greater than 3 is of the form 6k+/-1.
                  If you know the upper bound of the prime number, then the Sieve of Eratosthenes gives the answer much quickly.

    import java.util.ArrayList;
    import java.util.List;

    public class NthPrimeNumber {
    public static void main(String[] args) {
    int index = 5;

    if (index == 1) {
    System.out.println(2L);
    return;
    }

    // An array of all the discovered primes
    List<Long> primes = new ArrayList<Long>();
    primes.add(2L);

    Long num = 3L;

    // Search for primes by dividing num with all the known prime numbers
    while (primes.size() != index) {
    boolean isComposite = false;
    double sqrt = Math.sqrt(num);
    for (Long p : primes) {
    if (p > sqrt)
    break;
    if (num % p == 0) {
    isComposite = true;
    break;
    }
    }
    if (!isComposite)
    primes.add(num);
    num++;
    }
    System.out.println(primes.get(index - 1));
    }
    }

    Array inplace shuffle

    Given an array:

    [a_1, a_2, ..., a_N, b_1, b_2, ..., b_N, c_1, c_2, ..., c_N ]

    convert it to:

    [a_1, b_1, c_1, a_2, b_2, c_2, ..., a_N, b_N, c_N]

    in-place using constant extra space.

    Refer : http://www.ardendertat.com/2011/10/18/programming-interview-questions-9-convert-array/

    http://arxiv.org/PS_cache/arxiv/pdf/0805/0805.1598v1.pdf

    Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted

    Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted.

    Examples:
    1) If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between the indexes 3 and 8.

    2) If the input array is [0, 1, 15, 25, 6, 7, 30, 40, 50], your program should be able to find that the subarray lies between the indexes 2 and 5.

    Solution:
    1) Find the candidate unsorted subarray
    a) Scan from left to right and find the first element which is greater than the next element. Let s be the index of such an element. In the above example 1, s is 3 (index of 30).
    b) Scan from right to left and find the first element (first in right to left order) which is smaller than the next element (next in right to left order). Let e be the index of such an element. In the above example 1, e is 7 (index of 31).

    2) Check whether sorting the candidate unsorted subarray makes the complete array sorted or not. If not, then include more elements in the subarray.
    a) Find the minimum and maximum values in arr[s..e]. Let minimum and maximum values be min and max. min and max for [30, 25, 40, 32, 31] are 25 and 40 respectively.
    b) Find the first element (if there is any) in arr[0..s-1] which is greater than min, change s to index of this element. There is no such element in above example 1.
    c) Find the last element (if there is any) in arr[e+1..n-1] which is smaller than max, change e to index of this element. In the above example 1, e is changed to 8 (index of 35)

    3) Print s and e.

    Refer : http://www.geeksforgeeks.org/archives/8858

    Tuesday, February 14, 2012

    Maximum of two values using abs

    Given two number a and b,find out the maximum of two numbers?
    max(a,b) = (abs(a+b)+abs(a-b))/2;

    Balanced bit array

    You are given a bit array (i.e each element is 0 or 1) A[1..n].
    A bit array is called balanced if the number of times 01 appears is same as the number of times 10 appears. By 01 appearing we mean that A[i] = 0 and A[i+1] = 1 for some i.
    i.e.
    S1 = { i : A[i] = 0 and A[i+1] = 1}
    S2 = { j : A[j] = 1 and A[j+1] = 0}
    The array is balanced if number of elements in S1 is same as number of elements in S2.
    Eg: A = [1,0,1] is balanced.
    A = [0,0,0,0,0,0] is balanced too.
    Give an algortihm to determine if a bit array A[1...n] is balanced.

    Solution : 

    a simple way to explain this would be to consider this as a switch.
    0 - OFF state
    1 - ON state
    01  - switch going from OFF to ON.
    10 - switch going from ON to OFF.
    If the 1st and last element are the same then that means that the switch has been toggled even no. of times. Hence no. of 01's and 10's are equal.

    Count the number of numbers up to n which are both square and cube


    Count the number of numbers up to n which are both square and cube.
    e.g., for 1 < n < 1000 answer is 2 (64, 729)

    The numbers 0 and 1 are self-squares and self-cubes, all exponentials being 0 and 1 respectively. Only a few other numbers are both squares and cubes of integers.

    For any given square and cube, the numerical relation is n3 = [n(sqrt n)]2
    so for the value n where (sqrt n) is whole number, the cube of n is also a square.
    After 0 and 1, the next 4 are 64, 729, 4096, and 15625.

    64 = 43 = 82 . (4x2)2
    729 = 93 = 272 . (9x3)2
    4096 = 163= 642 . (16x4)2
    15625 = 253 = 1252 . (25x5)2

    You can find the others easily. There are each the sixth power of any integer,
    such that x6 = (x2)3 = (x3)2 e.g. 26 = 64, 36 = 729, 46 = 4096, etc. - Besides 64, another easy one is the number one million, 106, which is 1003 and 10002.

    We can say that these numbers are the cube of a square, or the square of a cube, for any given integer.

    Average of a stream of numbers

    Given a stream of numbers, print average (or mean) of the stream at every point. For example, let us consider the stream as 10, 20, 30, 40, 50, 60, …

      Average of 1 numbers is 10.00
      Average of 2 numbers is 15.00
      Average of 3 numbers is 20.00
      Average of 4 numbers is 25.00
      Average of 5 numbers is 30.00
      Average of 6 numbers is 35.00
      ..................

    Refer : http://www.geeksforgeeks.org/archives/15658

    Monday, February 13, 2012

    Dynamic programming

    Here is a link points to important resources of dynamic programming :
    http://avidullu.wordpress.com/2010/02/18/solution-to-dynamic-programming-problems/

    Medals puzzle

    In a sports contest there were m medals awarded on n successive days (n > 1).
    1. On the first day 1 medal and 1/7 of the remaining m - 1 medals were awarded.
    2. On the second day 2 medals and 1/7 of the now remaining medals was  awarded; and so on.
    3. On the nth and last day, the remaining n medals were awarded.

    How many days did the contest last, and how many medals were awarded  altogether?


    Total 36 medals were awarded and the contest was for 6 days.
    On day 1: Medals awarded = (1 + 35/7) = 6 : Remaining 30 medals
    On day 2: Medals awarded = (2 + 28/7) = 6 : Remaining 24 medals
    On day 3: Medals awarded = (3 + 21/7) = 6 : Remaining 18 medals
    On day 4: Medals awarded = (4 + 14/7) = 6 : Remaining 12 medals
    On day 5: Medals awarded = (5 +7/7) = 6 : Remaining 6 medals
    On day 6: Medals awarded 6

    Convert a number from one base to another

    Convert a number from given in base B1 to a number in base B2
    public class KthMaxSum {
    public static void main(String[] args) {
    int decimal = 10;
    int binary = 2;
    for (int i = 0; i < 20; i++) {
    convertBase(i, decimal, binary);
    }
    }

    private static void convertBase(int number, int fromBase, int toBase) {
    int result = 0, i = 0;
    while (number > 0) {
    result = result + (number % toBase)
    * (int) (Math.pow(fromBase, i++));
    number /= toBase;
    }
    System.out.println(result);
    }
    }

    Maximum number of nested envelopes

    You are given an unlimited number of each of n different types of envelopes. The dimensions of envelope type i are xi × yi. In nesting envelopes inside one another, you can place envelope A inside envelope B if and only if the dimensions A are strictly smaller than the dimensions of B.


    Algorithm to determine the largest number of envelopes that can be nested inside one another.?

    Solution:
    1. Sort all the xi's in ascending order -> nlog(n)
    2. Then find the longest increasing sequence of yi's -> nlog(n) 
    3. complexity will be nlog(n).

    Interleavings of two strings

    Given two strings str1 and str2, write a function that prints all interleavings of the given two strings. You may assume that all characters in both strings are different

    Example :
    Input: str1 = "AB",  str2 = "CD"
    Output:
        ABCD
        ACBD
        ACDB
        CABD
        CADB
        CDAB
    public class InterLeavedStrings {
    public static void main(String[] args) {
    String str1 = "abc";
    String str2 = "def";

    if (str1 != null && str1.length() != 0 && str2 != null
    && str2.length() != 0) {
    getInterLeavedStrings(str1, str2);
    getInterLeavedStrings(str2, str1);
    } else if (str1 == null || str1.length() == 0) {
    System.out.println(str2);
    } else {
    System.out.println(str1);
    }
    }

    private static void getInterLeavedStrings(String str1, String str2) {
    int m = str1.length();
    int n = str2.length();
    for (int i = 1; i < m; i++) {
    for (int j = 0; j < n; j++) {
    System.out.println(str1.substring(0, i) + str2.substring(0, j)
    + str1.substring(i, m) + str2.substring(j, n));
    }
    }
    }
    }


    Another variant of interleaving : Check a given string is interleaving of other two strings
     http://www.geeksforgeeks.org/archives/17750


    Refer : http://www.geeksforgeeks.org/archives/17743

    Minimum number of jumps to reach last element


    Problem: Given an array of integers, each element represents the max number of jumps can make forward. What is the minimum number of element selections to reach the end of the array (starting from the first element).
    Example: arr = 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9
    Here the min # of selections is : 3
    with the sequence : 1-> 3 -> 8 ->9
    First element is 1, so can only go to 3.
    Second element is 3, so can make at most 3 jumps: eg to 5 or 8 or 9.
    If an element is 0, then cannot make any jumps


    public class MinNumberOfJumps {
    private static int MAX = 23234;

    public static void main(String[] args) {
    int[] jumps = { 2, 3, 1, 1, 4 };
    int minJumps = getMinJumps(jumps, jumps.length);

    if (minJumps < MAX)
    System.out
    .println("Minimum number of jumps needed to reach the end of the array is : "
    + minJumps);
    else
    System.out.println("Cannot reach the end position of the array");
    }

    private static int getMinJumps(int[] jumps, int size) {
    //Boundry conditions
    if (jumps == null || size == 0 || jumps[0] == 0)
    return MAX;

    int[] dp = new int[size];
    //Initialization of dp[i]
    for (int i = 0; i < size; i++)
    dp[i] = MAX;

    dp[0] = 0;//no need to jump at first element

    for (int i = 1; i < size; i++) {
    for (int j = 0; j <= i; j++) {
    if (jumps[j] >= (i - j)) {//check if jump is possible from j to is
    if (dp[j] + 1 < dp[i]) //check if better solution available
    dp[i] = dp[j] + 1;
    }
    }
    }
    return dp[size - 1];
    }

    }

    Refer  : http://avidullu.wordpress.com/2011/01/12/dp-after-a-long-time/
    http://tech-queries.blogspot.in/2011/08/find-optimal-number-of-jumps-to-reach.html

    Tuesday, February 7, 2012

    All logical bit questions

    Linked list, Stack and queue questions