Amazon Interview Question
1. Create a comparator for dates (compare year, then month (if needed), then date (if needed)). Return <, > or =.
2. Add one month to date A (new date) and compare with date B.
If both equal then they are month apart.
If 'new date' is more than date B then less than month apart.
If 'new date' less than date B then more than month apart.
following is the complete code:
note: the dates need to be entered in chronological order
#include<iostream.h>
#include<conio.h>
struct dates
{int dd;
int mm;
int yyyy;
}d1,d2;
void check(int x,int y)
{if(x>y)
cout<<"more than a month apart";
if(x<y)
cout<<"less than a month apart";
}
void main()
{clrscr();
cin>>d1.dd>>d1.mm>>d1.yyyy;
cin>>d2.dd>>d2.mm>>d2.yyyy;
if(d1.yyyy==d2.yyyy)
if(d2.mm==((d1.mm)+1))
if(d2.dd==d1.dd)
cout<<"month apart";
else check(d2.dd,d1.dd);
else check(d2.mm,d1.mm);
else cout<<"more than a month apart";
getch();
}
I think we should not consider days.
1. Get month and year of first. - format YYYYMM
2. Get month and year of second. -- YYYYMM
3. if first > second
check month of second, if 12, make it 01 and add 1 to the year
if first < second
check month of first, if 12, make it 01 and add 1 to the year
4. Subtract first - second
If 0 = months apart
1) Create a hash table containing month numbers or names as key and their respective no. of days in a month
- Mandar December 19, 20092) Then find then difference between months of dates (Exceptions december and january)
3) then check if the day field is same in both dates, if yes then x no. of months apart, if not well then subtarct the no.of days from first months no. of days as per hash table and add to no. of days from day field in second date that makes them that much days apart.