Contents

Compare Dates (with.Java)

   Nov 27, 2023     2 min read

This is the ā€œCompare Datesā€ problem.

Weā€™re going to learn by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them.

Letā€™s start with the problem

Problem

You are given two integer arrays date1 and date2.

Each of the two arrays represents a date and is given in the form [year, month, day], where year represents the year, month represents the month, and day represents the day.

Complete the solution function to return 1 if date1 is earlier than date2, or 0 otherwise.

Example input and output

date1date2result
[2021, 12, 28][2021, 12, 29]1
[1024, 10, 24][1024, 10, 24]0

My solution to the ### problem

class Solution {
    public int solution(int[] date1, int[] date2) {
        int answer = 0;
        for(int i = 2; i >= 0; i--){
            if(date1[i] < date2[i]){
                answer = 1;
            }else if(date1[i] > date2[i]){
                answer = 0;
            }
        }
    } return answer;
}

solution description

int answer = 0;: Initialize an integer variable, answer, to store the result. The initial value is 0.

for(int i = 2; i >= 0; iā€“) : Compares each date field (year, month, day) using a loop starting at 2 and iterating down to 0. The loop starts with the year and compares in the following order: year, month, day.

if(date1[i] < date2[i]): If the value of date1 is less than the value of date2 in the current field:

Set answer to 1. This indicates when date1 is earlier than date2 . else if(date1[i] > date2[i]) : If the value of date1 is greater than the value of date2 in the current field:

Set answer to 0. This indicates when date1 is later than date2.

return answer;: Returns the value of answer, which represents the result of comparing the dates.