Microsoft OA Day of week that is K days later Solution

Microsoft Online Assessment Day of week that is K days later Leetcode

Given a day of the week, with an integer K representing numbers, find the day of the week after K days.

Also See: Microsoft Online Assessment Questions and Solution

Example 1:

Input:

day = “Monday”

K = 3

Output: Thursday

Solution

Program C++:

Day of week that is K days later Leetcode

By description we have as input parameters: string with name of day of week and distance in days till another day of week. We have to find name of the second day of week and return a string with it’s name. To solve this task it would be good to convert given day of week from string to a number of day. Let’s count the days from 0. That is Sunday is 0, Monday is 1 … Saturday is 6.

Then we have a distance between two days of week in days. And we need to find out which day of week is the last day on this distance. Or in other words which number of the day inside of week.

Each week contains 7 days so in order to find a number of day of week we need to convert the distance between of these days from days to weeks. It is easy to calculate the distance in weeks if we have integer number of weeks between the given days.

For example if we have S = “Sun” and K = 7, a day of week in 7 days is “Sun” too.

But if the distance is not divided entirely we may use the remainder after division by 7 it order to find a number of day within a week. For example let’s S = “Tue” and K = 10. Tuesday is 2 day of week. We should add to 10 to 2. 10+2=12 and divide 12 by 7. We get remainder = 5.

Thus day of week of the last day is Friday because 5th day of week is Friday and there are 10 days between Tuesday this week and Friday next week.

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>

using namespace std;

string solution(const string &day, int k) {
    vector<string> days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    unordered_map<string, int> week_map = {{"Sun", 0},
                                           {"Mon", 1},
                                           {"Tue", 2},
                                           {"Wed", 3},
                                           {"Thu", 4},
                                           {"Fri", 5},
                                           {"Sat", 6}};

    return days[(week_map[day] + k) % 7];
}

int main() {

    cout << solution("Sat", 23) << " Expected: Mon" << endl;

    return 0;
}

Also See: AMCAT Study Materials, Preparation Guide

Also See: Amazon OA Online Assessment 2021 Questions and Answers

Microsoft Online Assessment 2021 Questions

Leave a Comment