Showing posts with label math. Show all posts
Showing posts with label math. Show all posts

Sunday, March 9, 2014

Find number of ways to go n steps with 1 or 2 steps

Problem:
Frog can jump 1 or 2 steps write the code to find out number of ways to go up to n steps.

Solution:

The number of ways to jump to n steps is the n-th Fibonacci number!

F[n] = F[n-1] + F[n-2]; 
F1 = 1; F2 = 2;

Example:

F[3] = F[2] + F[1]
1 1 1 part of F[2]
2 1 part of F[2]
1 2 part of F[1]

F[2]
1 1 
2

F[1]
1

Complexity:
time - O(n)
space - O(1) (for iterative approach)
Links and credits:
http://www.careercup.com/question?id=5950229446656000

Tuesday, March 4, 2014

Sort n numbers in range from 0 to n^2 – 1 in linear time

Problem:
Given an array of numbers of size n. It is also given that the array elements are in range from 0 to n2 – 1. Sort the given array in linear time.

Examples:
Since there are 5 elements, the elements can be from 0 to 24.
Input: arr[] = {0, 23, 14, 12, 9}
Output: arr[] = {0, 9, 12, 14, 23}

Since there are 3 elements, the elements can be from 0 to 8.
Input: arr[] = {7, 0, 2}
Output: arr[] = {0, 2, 7}

Solution:
The idea is to use Radix Sort. Following is standard Radix Sort algorithm.

Do following for each digit i where i varies from least significant digit to the most significant digit: Sort input array using counting sort (or any stable sort) according to the i’th digit.

Let there be d digits in input integers. Radix Sort takes O(d*(n+b)) time where b is the base for representing numbers, for example, for decimal system, b is 10. Since n2-1 is the maximum possible value, the value of d would be O(\log_b(n)). So overall time complexity is O((n+b)*\log_b(n)). Which looks more than the time complexity of comparison based sorting algorithms for a large k. The idea is to change base b. If we set b as n, the value of O(\log_b(n)) becomes O(1) and overall time complexity becomes O(n).

arr[] = {0, 10, 13, 12, 7}

Let us consider the elements in base 5. For example 13 in
base 5 is 23, and 7 in base 5 is 12.
arr[] = {00(0), 20(10), 23(13), 22(12), 12(7)}

After first iteration (Sorting according to the last digit in 
base 5),  we get.
arr[] = {00(0), 20(10), 12(7), 22(12), 23(13)}

After second iteration, we get
arr[] = {00(0), 12(7), 20(10), 22(12), 23(13)}

How to sort if range is from 1 to n2?
If range is from 1 to n n2, the above process can not be directly applied, it must be changed. Consider n = 100 and range from 1 to 10000. Since the base is 100, a digit must be from 0 to 99 and there should be 2 digits in the numbers. But the number 10000 has more than 2 digits. So to sort numbers in a range from 1 to n2, we can use following process.
1) Subtract all numbers by 1.
2) Since the range is now 0 to n2, do counting sort twice as done in the above implementation.
3) After the elements are sorted, add 1 to all numbers to obtain the original numbers.

How to sort if range is from 0 to n^3 -1?
Since there can be 3 digits in base n, we need to call counting sort 3 times.


PS. Note: the counting sort for the radix sort for base n requires O(n) memory. We could try to use a bit-set for sorting if all the numbers are unique.

Complexity:
time - O(n)
space - O(n) (for counting sort)
Links and credits:
http://www.geeksforgeeks.org/sort-n-numbers-range-0-n2-1-linear-time/

Sunday, February 2, 2014

Find elements with sum equal to the sum of their indexes

Problem:
Write a method which takes an array input and returns true if the sum of any two elements is equal to the sum of the corresponding indices. Like if for an array the sum of values at any two indices i and j is equal to the sum of i and j.

Solution:
Since we know we are looking for pairs where x+y = A[x] + A[y], by simple algebra, you can also look for x-A[x] = A[y]-y

public static ArrayList<ArrayList<Integer>> findSums(int[] A) {
  // Look for pairs where  x - A[x] == A[y] - y
  ArrayList<ArrayList<Integer>> soln = new ArrayList<ArrayList<Integer>>();
  HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();
  
  for (int x = 0; x < A.length; x++) {
   h.put(x-A[x],x);
  }
  
  for (int y = 0; y < A.length; y++) {
   if (h.containsKey(A[y]-y)) {
    int x = h.get(A[y]-y);
    if (y != x) {
     ArrayList<Integer> pair= new ArrayList<Integer>();
     pair.add(x);
     pair.add(y);
     soln.add(pair);
    }
   }
  }
  
  return soln;
}

Complexity:
time - O(n)
space - O(n)
Links and credits:
http://www.careercup.com/question?id=5705699820568576

Tuesday, January 14, 2014

Find longest subarray with equal sum

Problem:
Given 2 binary arrays A and B i.e. containing only 0s and 1s each of size N.
Find indices i,j such that Sum of elements from i to j in both arrays is equal and j-i (i.e. the length of the set i,j) is the maximum possible value.

Solution:
This is same as finding the longest subarray with sum zero in the array C[i] = A[i] - B[i].

Prefix sums + hashtable should give it.

Complexity:
time - O(n)
space - O(n)
Links and credits:
http://www.careercup.com/question?id=25036663

Sunday, January 12, 2014

Find a subarray divisible by 7

Problem:
WAP a program to find a contineous subset whose sum is divisible by 7. We are given a array of number (negative+positive).
calculate the complexity of your algorithm

Solution:
So, we want to find sub-set [i, j], such that

a[i]+a[i+1]+ ... a[j] ) % k = 0

with k == 7, that really does not matter
________________________________________________
Let's calculate the sum of elements from 1 to i by mod k for each i:

s[i] = (a[1] + a[2] + ... + a[i]) % k

And we can note that, if there is such [i, j] that we are looking for, then:

s[j]-s[i] == (a[1]+...+a[j]) - (a[1]+...+a[i]) == (a[i]+...+a[j]) == 0

So, for each s[i] == s[j], sum of sub-set [i, j] is divisible by k.

Complexity:
time - O(n)
space - O(n)
Links and credits:
http://www.careercup.com/question?id=5812734516002816

Saturday, October 12, 2013

Integer to Roman

Problem:
Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Solution:

public String intToRoman(int num) {
    int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
    StringBuilder res = new StringBuilder();
    int i=0;
    while (num>0) {
        int times = num / nums[i];
        num -= nums[i]*times;
        for (; times>0; times--) {
            res.append(symbols[i]);
        }
        ++i;
    }
    return res.toString();
}


Complexity:
time - O(1)
space - O(1)
Links and credits:
http://discuss.leetcode.com/questions/194/integer-to-roman

Sunday, September 29, 2013

Palindrome Number

Problem:
Determine whether an integer is a palindrome. Do this without extra space.

Solution:
First, compare the first and last digit. If they are not the same, it must not be a palindrome. If they are the same, chop off one digit from both ends and continue until you have no digits left, which you conclude that it must be a palindrome.

Now, getting and chopping the last digit is easy. However, getting and chopping the first digit in a generic way requires some thought.

bool isPalindrome(int x) {
    if (x < 0) return false;
    int div = 1;
    while (x / div >= 10) {
        div *= 10;
    }
    while (x != 0) {
        int l = x / div;
        int r = x % 10;
        if (l != r) return false;
        x = (x % div) / 10;
        div /= 100;
    }
    return true;
}


Complexity:
time - O(1)
space - O(1)
Links and credits:
http://discuss.leetcode.com/questions/181/palindrome-number

Sunday, August 18, 2013

Find a missing number

Problem:
Given you an array of 100 Elements with one number missing, how will you find the missing number?

Ex.: Array 1 to 100 with 55 missing.

Solution:
Just do sum of all the numbers from 1 to 100 : (n * (n+1))/2 and find sum of all the elements from actual array. Just take the difference and you will get missing number.
If numbers start with n > 1, then normalize them by subtracting n-1.

Complexity:
time - O(n)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=23092662
See also: Find two missing numbers

Calculate (x^y)%z without pow()

Problem:
Calculate (x^y)%z without pow().

Solution:
The question here is how we can reduce the complexity... if we compute the x^y by normal method the complexity is O(y)... to reduce the complexity we can use binary weighted power computation method in which complexity is O(logy)..

ans=1;
square=x;
if(y==0)
    return 1;
while(y!=0)
{
    if(y%2)
        ans=ans*square;
    square=(square*square)%z;
    y=y/2;
    if(ans>z)
        ans=ans%z;
}
return ans;


Complexity:
time - O(log n)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=22767685

Monday, August 12, 2013

Find square root of an integer without using built in functions

Problem:
Find square root of an integer without using built in functions.

Solution:
Provided we don't know or can't recall any math: square roots of integer numbers are "sorted" in a way that the grater the number, the greater its square root is. So we can use binary search starting with the interval (0; n) and set x = (n - 0) / 2, continuing dividing the interval until we get | x*x - n | < epsilon, where the epsilon is some very small number (e.g. 0.0000000001).

Complexity:
time - O( ??? ) - I'd speculate something like O (log n / epsilon). log n comes from using the binary search, and obviously, the higher the required precision, the longer the search takes, hence the (1 / epsilon) multiplier.
space - O(1)
Links and credits:
http://www.careercup.com/question?id=6657802751705088

Sunday, July 7, 2013

Find Nth number in x2x3x5 sequence

Problem:
Following sequence is given:
1,2,3,4,5,6,8,9,10,12,15,16,18,20,24
In this sequence, each number is multiple of 2,3 or 5 only.
This sequence does not contain 7 & 14 as these number has sequence 7 as multiple.
So, if you are given N find the Nth number of this sequence.

Solution:
A dynamic programming solution (assume the sequence starts with 2):
  1. Maintain a counter, that is initialized to 1 and start from an initial value v, say 2. 
  2. Keep incrementing the value v and check if it is divisible by 2 or 3 or 5. 
  3. If divisible, check if the corresponding quotient of v/2 or v/3 or v/5 is present in the solutions to subproblems, that are already computed. If yes increment the counter. 
  4. Return value v when the counter becomes N.
void findN(int N) {
    HashMap<Integer, Integer> DPMap = new HashMap<Integer, Integer>();
    int temp = 2, i = 1;
    DPMap.put(1, 1);
    DPMap.put(2, 2);

    while (i < N) {
        temp++;
        if ((temp % 2 == 0 && DPMap.containsKey(temp / 2))
                || (temp % 3 == 0 && DPMap.containsKey(temp / 3))
                || (temp % 5 == 0 && DPMap.containsKey(temp / 5)))
        {
            i++;
            DPMap.put(temp, temp);
        }
    }
    System.out.println("The required number = " + temp);
}


Complexity:
time - O(n)
space - O(n)
Links and credits:
http://www.careercup.com/question?id=20810664

Monday, June 24, 2013

Count bits in an integer

Problem:
Count the no. of 1's in an integer.

Solution:

Solution #1: The most straightforward approach is to check each bit one by one. Here is the code,

int count1(int n)
{
    int count=0;

    while(n)
    {
        if(n&1)
            count++;

        n = n>>1;
    }

    return count;
}

Solution #2: The below code is an efficient version which improves the average time.
This code is faster because on each iteration it always clears the LSB of the number.

int count2(int n)
{
    int count=0;

    while(n)
    {
        count++;
        n = n&(n-1);
    }

    return count;
}

Complexity:
time - O(1)
space - O(1)
Links and credits:
http://puddleofriddles.blogspot.ru/2012/03/count-bits-in-integer.html

Sunday, June 23, 2013

Modify bits x...y in an integer

Problem:
given two integers and two bit positions. Set the first integer between the two bit positions to be that of the second integer.

Solution:
The trickiest part is to calculate the mask:

int replace_bits(int a, int b, int x, int y) 
{ 
    int mask = ((1 << (y - x + 1)) - 1) << x; 
    // Clear a and replace with that of b 
    return ((a & ~mask) | (b & mask)); 
}

Complexity:
time - O(1)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=13532675

Calculate ceiling (y / x) w/o using % (modulo)

Problem:
given y bytes and you can transfer only x bytes at once..give a mathematical expression having only + - / * which gives the number of iterations to copy y bytes. ( dont try giving modulo operator answers )

Solution:

ceiling(y / x) = (y + (x - 1)) / x

In order to prove correctness you need to check two case sets:
1. y % x == 0 => addition of x-1 doesn't affect the result, so it is y/x (which is ok)
2. y % x > 0 => addition of x-1 increments result with 1 (which is ok because we need another copy for the remaining y % x bytes).

Complexity:
time - O(1)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=14911702

Saturday, June 22, 2013

Print a decimal number in binary form

Problem:
Print a decimal number in binary form. eg: number=10 or 2.22 or 0.876 ....
Required to print only four number after decimal point.

Solution:
Subsequently divide the integer part by two, and then multiply the fractional part by two.

def dec2bin(number):
    ## integer part:
    int_number = int(number)
    int_bin_str = ''
    while int_number != 0:
        (int_number, remainder) = divmod(int_number, 2)
        int_bin_str = str(remainder) + int_bin_str

    ## fractional part
    frac_number = number - int(number)
    frac_bin_str = ''
    count = 0
    while( count < 4):
        frac_bin_str += str(int(2.0 * frac_number))
        frac_number  = 2*frac_number - int(2*frac_number)
        count += 1

    return int_bin_str+"."+frac_bin_str

## MAIN ##
print dec2bin(10)
print dec2bin(2.22)
print dec2bin(0.876)


Complexity:
time - O(n)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=19883663

Saturday, June 15, 2013

Determine the average salary w/o revealing individual salaries

Problem:
There are three people and they need to know the average of their salaries without knowing each other's salary. How will you do that?

Solution:
1. Here's a simple solution. We start out assuming everyone's salary is in a certain range, say 0 - 1 trillion. The first person picks a number uniformly at random in that range and informs only the second person about this random number. Since this number is just random, it conveys no information. The second person adds their salary to the number and informs the third person about this sum. The third person receives no info from this because of the random element added in. The third person adds their salary to this running total and informs the first person about the sum. The first person knows the random number and subtracts it out, leaving the first person with the sum of the second and third person's salary. The first person could have obtained this info from the average anyway, so no extra information has been conveyed. Finally the first person adds their salary and divides by 3.

2. More secure solution: Have them pick "two" random numbers and reveal the sum of two random numbers and their salary, then sum them all up. Each developer now exchanges one of their random numbers. Now, when they subtract random numbers from the total, none of them can guess each other's salary.
Once the random numbers are subtracted, divide it by 3, which is the average salary of three developer.

The added security is to avoid the third person disclosing the sum given by the second person in the first solution. Otherwise the first person could determine the salary of the second person.

Complexity:
time - O(n)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=14184700
http://www.careercup.com/question?id=19694667

Sunday, June 2, 2013

Compute a partial sum of array using plus operator only

Problem:
There's an array of numbers A[1]...A[N]. Need to compute another array of numbers S[1]...S[N] such that each S[i] is a sum of all the elements A[1]...A[N] except the element A[i]. In other words:

S[i] = ƩA[j], 1 <= j <= N && j != i

Solution:
We need two passes over the array A[]. One to compute the sum in the forward direction (1..N) and assign the accumulated sum to each S[i] element. Another pass is performed in the backward direction (N..1) and adds the accumulated sum to the corresponding S[i] element. Each of the passes ensures that the sum accumulated in S[i] does not contain the value of A[i] itself:

1. take a variable say, Sum, initialize it as Sum = 0. 
2. For index i=1 to N do : 
      S[i] = Sum; 
      Sum+=A[i]; 
3. Sum = 0; 
4. For index i=N down to 1 do: 
      S[i]+=Sum; 
      Sum+=A[i]; 
5. Done.


Complexity:
time - O(n)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=19301668


Thursday, May 23, 2013

Find two missing numbers

There's an array of 100 numbers. Another array contains only 98 numbers from the first one. Identify two missing numbers.

Constraints:
  • Space complexity must be O(1).
    So you can't use any other data structure like a hash-map, etc.
  • The arrays are immutable.
    So you can't e.g. sort them.
Math is your friend. For both arrays you need to count a sum of all numbers (sum and sum2), and a sum of squares of the numbers (sq_sum, sq_sum2). Then:

sum - sum2 = a + b
sq_sum - sq_sum2 = a^2 + b^2

(a + b)(a + b) = a^2 + b^2 + 2ab
(a + b)(a + b) - (a^2 + b^2) = 2ab
(sum*sum - sq_sum) = 2ab

(a - b)(a - b) = a^2 + b^2 - 2ab
               = sq_sum - (sum*sum - sq_sum) = 2sq_sum - sum*sum
sqrt(2sq_sum - sum*sum) = sqrt((a - b)(a - b)) = a - b
((a + b) - (a - b)) / 2 = b
(a + b) - b = a

Credit: see link below.

Complexity:
time O(N)
space O(1)