Amazon Interview Question
Software Engineer / DevelopersI think the point should be to minimize the number of arithematic and comparison operations, not just get the right answer. So a number of pruning steps are required to return false.
1. if difference between years >= 2 then false
2. if difference between month names >= 2, like "Jan" and "Apr" (1 and 4) then false
now you serialize the date, by 1 being the first date of the smaller month, +30 (or whatever) being the first date of the second month (include difference in year too).. then convert both dates into this format, subtract, and see if its less than 30 days..
Also cases like February, with 28 days, might need to be special cases.
Date1:
D1YY
D1MM
D1DD
Date2:
D2YY
D2MM
D2DD
If |D2YY - D1YY| > 1 => More than month apart
If |D2YY - D1YY| = 0 => Same Year
If |D2MM - D1MM | > 1 => More than a month apart
If |D2MM - D1MM| = 0 => Same month => Less than month apart
If |D2MM - D1MM| = 1
If |D2DD - D1DD| = 0 => Month Apart
If D2MM > D1MM
If D2DD > D1DD => More than a month
else => Less than a month
else
If D1DD > D2DD => More than a month
else => Less than a month
and so on... it is so tiring to write all this :)
example:
dd/mm/yyyy
-Assuming no leap years
-All months have 30 days
date1 = 04/06/2007
date2 = 09/07/2007
compute date1 and date2 as follows:
date1 = 2006*365 + 6*30 + 4
date2 = 2006*365 + 7*30 + 9
check modulus of |date2 - date1| > 30
If we are allowed to use a method that given a date converts it into number of seconds from Jan 1 1970.
And then consider a month as 4 weeks = 28 days and just check if the difference between the dates in 28 days?
If we need to be strict abt 30,31,28 write up some if statements...
Its a good and smart solution but it can error.
suppose we want to find number of days between 12/5/1699 and 1/1/1704.
By using system time, you port both the time to the current times so that it fits within our 1970 case.
So first date becomes 12/5/1970 and second one 1/1/1975. Here there is a leap year between these dates i.e. 1972. In the original dates there is no leap year since 1700 is not a leap year.
Assume these two functions :
- Anonymous October 14, 20061. addMonths(date, n): Adds exactly 'n' months to 'date'
2. compare(date1, date2): Returns -1, 0, 1 depending on the date values
These functions are very easy to code. Then the solution for the problem will be the following function:
// this function returns
// -1 if the two dates are less than one month apart
// 0 if the two dates are exactly one month apart
// 1 if the two dates are more than one month apart
int compareDateMonths(Date date1, Date date2)
{
Date earlier;
Date later;
int comparison = compare (date1, date2);
if ( comparison == 0)
{
return -1;
}
else if (comparison == -1)
{
earlier = date1;
later = date2;
}
else
{
earlier = date2;
later = date1;
}
addMonths(earlier, 1);
return -(compare(earlier, later));
}