Showing posts with label logic. Show all posts
Showing posts with label logic. Show all posts

Thursday, March 22, 2012

Can you write a palindrome function?

Can you write a palindrome function?

Yes, sure! Here is a very simple one, case sensitive, without handling special characters:

package com.blogspot.interviewqa4java;

/** © 2012 interviewqa4java.blogspot.com */
public class Palindrome {
  
    public static void main(String[] args) {
        String[] words= {"ABCBA", "ABCCBA", "AAC", "ABAB"};
        for (String word : words) {
            System.out.println("Is \'"+ word + "\' a palindrome? "+ isPalindrome(word));
        }
    }

    private static boolean isPalindrome(String word) {
        for (int i = 0, j=word.length()-1; i < (word.length() / 2); i++, j--) {
            if(word.charAt(i) != word.charAt(j)){
                return false;
            }
        }
        return true;
    }
}


Console results:
Is 'ABCBA' a palindrome? true
Is 'ABCCBA' a palindrome? true
Is 'AAC' a palindrome? false
Is 'ABAB' a palindrome? false

Thursday, February 9, 2012

How do I multiply 2 big integers?

How do I multiply 2 big integers?
In the previous post I talked about "How do I add 2 big integers?". In the same scenario, consider that now you want to multiply those 2 huge integer numbers... Is the logic the same?

Yes, but the solution is not as simple. Please read the previous post to understand the logic behind the solution, then jump to the code and see my comments bellow.

[Java code snippet] Big integer product

First, note that we are iterating over both big integer representations as arrays – array1 and array2. On line 22 you can see the product of 2 single-digits items that represent the i-est and j-est digits of both big integers, respectively. 

As commented on line 25, if the product has 2 digits, the 2nd one should be stored in the next index. Since the current index is given by i+j, the next one will be i+j+1. To implement this logic, we will iterate over the array representation of this product, called prodAsArray, where k could be 0 or 1 (line 26).

When we are storing each digit on its correct position i+j+k (line 27), we have to add the it to the previous digit that might have been stored in a previous iteration. That's why I used +=. Ops, a sum operation, so the result could also have 2 digits! If it is the case, we have lines 30 to 38 to handle this, following the same logic as described before.

How do I add 2 big integers?

How do I add 2 big integers?
Say you want to add 2 integer numbers that are so huge that you can't just add them directly and you can't use an API like BigInteger; you have to implement the sum operation. What would you do?

The solution here is simple. Each huge integer number will be represented using an  int array[ ]. Each digit will be stored in a different position in the array. E.g.: 2012 --> [2, 1, 0, 2]

Considering that 2012 = (2*10^0 + 1*10^1 + 0*10^2 + 2*10^3 ),  then 2012 + 35= ((2+5)*10^0 + (1+3)*10^1 + (0+0)*10^2 + (2+0)*10^3 )   = 2047

So, all you have to do is to sum items in the same index, right?Almost! Remember to consider the carry: store it if the sum  > 9 and then use it in the next index sum. Well, enough of talking, let's see the code! First let's see the main() method and the add logic:

[Java code snippet] Big integer sum

 If you're interested in the details, take a look at the Big integer auxiliary methods, that also can be used for Big integer product, in a later post...

[Java code snippet] Big integer auxiliary methods


And here, the code so you can copy and run using Eclipse, NetBeans, etc.

package ric.interviewqa4java;

/** © 2012 interviewqa4java.blogspot.com */
public class BigInteger {
    public static void main(String[] args) {
        int bigInt1 = Integer.MAX_VALUE;
        int bigInt2 = Integer.MAX_VALUE;
   
        System.out.println(bigInt1+" + "+bigInt2+" = "+add(bigInt1, bigInt2));
    }
   
    public static String add(int bigInt1, int bigInt2) {
        //Find array length
        int length1 = intLenght(bigInt1);
        int length2 = intLenght(bigInt2);
        int arrayLength = Math.max(length1, length2);
               
        //convert numbers into array; Ex: 157 -> [7, 5, 1, 0, 0]
        int array1[] = intToArray(bigInt1, length1, arrayLength);
        int array2[] = intToArray(bigInt2, length2, arrayLength);
       
        //sum arrays
        return sumArray(array1, array2);
    }
   
    /** Solution logic here*/
    private static String sumArray(int[] array1, int[] array2) {
        int carry=0;
        int sumArray[] = new int[array1.length + 1];
       
        //sum arrays
        for (int i = 0; i < array1.length; i++) {
            sumArray[i] = (array1[i] + array2[i] + carry) % 10 ; //sum digits + carry; then extract last digit
            carry = (array1[i] + array2[i] + carry) / 10; //Compute carry
        }
        sumArray[array1.length] = carry;
        return arrayToString(sumArray);
    }
   
    /** Auxiliary methods*/
    private static int intLenght(int bigInt) {
        return Integer.toString(bigInt).length();
    }
    private static int[] intToArray(int bigInt, int bigIntLength, int arrayLength) {
       
        int array[] = new int[arrayLength ];
        for (int i = 0; i < arrayLength ; i++) {
            array[i] = ( i<bigIntLength ?
                             getDigitAtIndex(bigInt, bigIntLength - i -1) :
                             0 ); //complete the rest of the array with 0
        }
        return array;
    }
    private static int getDigitAtIndex(int longint,int index){       
        return Integer.parseInt(Integer.toString(longint).substring(index, index+1));
    }
    private static String arrayToString(int[] sumArray) {
        String sum = "";
        boolean firstNonZero = false;
        for (int i = sumArray.length-1; i >= 0 ; i--) { //from array end to beginning
           
            if(!firstNonZero && (sumArray[i]==0)){ //ignore if 1st digits are 0
                continue;
            } else{
                firstNonZero=true;
            }
            sum += sumArray[i];
            if((i%3 ==0)&&i!=0){ sum +=",";}  //formatting
        }
        String sumStr = sum.length()==0?"0":sum; // handle the 0 value (haha, input was not big!)
        return sumStr;
    }
}

Thursday, January 19, 2012

How do you find if a Java array has duplicates?

How do you find if a Java array has duplicates?


Say you have a int[] hugeArray and want to find if it has huplicates in an efficient way, without iterating over the hugeArray twice – which is O(n²). You could use a HashSet, so the code will be like this (Java code snipet as image and as text, so you can copy):

[Java code snipet] Array has duplicates


/** © 2012 interviewqa4java.blogspot.com */
private static boolean hasDuplicates(int[] hugeArray) {
        Set<Integer> set = new HashSet<Integer>();
        for (int element : hugeArray) {
            if(set.contains(element)){
                return true;
            }
            set.add(element);
        }
        return false;
    }






Tuesday, January 17, 2012

Given 2 time intervals, how do you find out if there is overlap between them?

Given 2 time intervals, how do you find out if there is overlap between them?

Say you have 2 time intervals ti1 = [t1, t2] and ti2 = [t3, t4]. You can say that there is overlap between ti1and ti2  if and only if  ( (t1 < t4) AND (t2 > t3) ).


Time interval overlap

Here is my Java code snippet.
[Java code snipet] Time interval


package ric.interviewqa4java;
import java.util.Date;

@SuppressWarnings("deprecation")
/** © 2012 interviewqa4java.blogspot.com */
public class TimeIntervalProblem {
   
    public static void main(String[] args) {
       
        TimeIntervalProblem.Interval interval1=null, interval2=null;
        interval1 = new TimeIntervalProblem().new Interval(new Date("2010/1/1"), new Date("2013/1/1"));
        interval2 = new TimeIntervalProblem().new Interval(new Date("2012/1/1"), new Date("2014/1/1"));
       
        boolean result =isThereOverlap(interval1, interval2);
        System.out.println("Is there overlap between "+ interval1 + " and "+ interval2 + "? " + result);       
    }
    //Solution logic here
    private static boolean isThereOverlap(Interval t1, Interval t2) {
        return t1.begin.before(t2.end) && t1.end.after(t2.begin);
    }

     private class Interval{
        private Date begin;
        private Date end;
        private Interval(Date begin, Date end) { this.begin = begin; this.end = end;}
        @Override
        public String toString() {
            return "[" + toString(begin) + ", " + toString(end) + "]";
        }
        private String toString(Date Date) {
            return ""+(1900+Date.getYear())+"-"+(1+Date.getMonth())+"-"+Date.getDate();
        }       
    }
}

Wednesday, January 4, 2012

Write a Java code snippet to calculate the sum of the first 100 numbers in the Fibonacci sequence

Write a Java code snippet to calculate the sum of the first 100 numbers in the Fibonacci sequence

Fibonnaci numbers follow this rule:
  • F(0) = 0;
  • F(1) = 1;
  • F(n) = F(n-1) + F(n-2), n ≥ 2, n is integer
The first 10 numbers in the Fibonacci sequence are: 0, 1, 1*, 2, 3, 5, 8, 13, 21 and 34. Note that the number 1 appears twice in the sequence, by definition.

Here is my Java code snipet (as image and as text, so you can copy):