loading...

Daily Coding Challenge #164

wingkwong profile image Wing-Kam WONG ・7 min read

About

This is a series of Daily Coding Challenge. Each day I show a few solutions written in C++. The questions are from coding practice/contest sites such as HackerRank, LeetCode, Codeforces, Atcoder and etc.


/*
Slowest Key
https://leetcode.com/problems/slowest-key/

A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.

You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.

The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].

Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.

Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.



Example 1:

Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
Output: "c"
Explanation: The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
Example 2:

Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"
Output: "a"
Explanation: The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.


Constraints:

releaseTimes.length == n
keysPressed.length == n
2 <= n <= 1000
0 <= releaseTimes[i] <= 109
releaseTimes[i] < releaseTimes[i+1]
keysPressed contains only lowercase English letters.
*/

class Solution {
public:
    char slowestKey(vector<int>& releaseTimes, string keysPressed) {
        char ans = keysPressed[0]; int time = releaseTimes[0]; 
        for(int i = 1; i < releaseTimes.size(); i++) {
            int t = releaseTimes[i] - releaseTimes[i - 1];
            if(t > time || t == time && keysPressed[i] > ans) {
                time = t;
                ans = keysPressed[i];
            }
        }
        return ans;
    }
};
Enter fullscreen mode Exit fullscreen mode

/*
Arithmetic Subarrays
https://leetcode.com/problems/arithmetic-subarrays/

A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.

For example, these are arithmetic sequences:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not arithmetic:

1, 1, 2, 5, 7
You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed.

Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.



Example 1:

Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]
Output: [true,false,true]
Explanation:
In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.
In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence.
Example 2:

Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]
Output: [false,true,false,false,true,true]


Constraints:

n == nums.length
m == l.length
m == r.length
2 <= n <= 500
1 <= m <= 500
0 <= l[i] < r[i] < n
-105 <= nums[i] <= 105
*/

class Solution {
public:
    bool isArithmetic(vector<int>& a) {
        int n = (int) a.size();
        sort(a.begin(), a.end());
        for(int i = 0; i + 1 < n; i++) {
            if(a[i + 1] - a[i] != a[1] - a[0]) return false;
        }
        return true;
    } 
    vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {
        int n = (int) l.size();
        vector<bool> ans;
        for(int i = 0; i < n; i++) {
            int left = l[i], right = r[i];
            auto start = nums.begin() + left, end = nums.begin() + right + 1;
            vector<int> tmp(right - left + 1); 
            copy(start, end, tmp.begin()); 
            ans.push_back(isArithmetic(tmp));
        }
        return ans;
    }
};
Enter fullscreen mode Exit fullscreen mode

/*
Path With Minimum Effort
https://leetcode.com/problems/path-with-minimum-effort/

You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.

A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.

Return the minimum effort required to travel from the top-left cell to the bottom-right cell.



Example 1:



Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
Example 2:



Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
Example 3:


Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.


Constraints:

rows == heights.length
columns == heights[i].length
1 <= rows, columns <= 100
1 <= heights[i][j] <= 106
*/

// AC - binary search + dfs
class Solution {
public:
    int dirx[4]={ -1, 0, 0, 1 };
    int diry[4]={ 0, 1, -1, 0 };
    void dfs(vector<vector<int>>& heights, vector<vector<int>>& vis, int i, int j, int mid) {
        vis[i][j] = 1;
        for(int d = 0; d < 4; d++) {
            int x = i + dirx[d], y = j + diry[d];
            if(x < 0 || x >= heights.size() || y < 0 || y >= heights[0].size() || vis[x][y]) continue;
            if(abs(heights[i][j] - heights[x][y]) > mid) continue;
            dfs(heights, vis, x, y, mid);
        }
    }

    int minimumEffortPath(vector<vector<int>>& heights) {
        int m = (int) heights.size(), n = m ? (int) heights[0].size() : 0;
        int l = 0, r = 1e6;
        while(l < r) {
            int mid = l + (r - l) / 2;
            vector<vector<int>> vis(m, vector<int>(n, 0));
            dfs(heights, vis, 0, 0, mid);
            if(vis[m - 1][n - 1]) r = mid;
            else l = mid + 1;
        }
        return l;
    }
};

// Contest Solution - TLE
class Solution {
public:
    vector<int> path;
    vector<int> ans;
    int t;

    bool ok(int i, int j, vector<vector<int>>& vis){
        return i>=0&&i<(int)vis[0].size()&&j>=0&&j<(int)vis[0].size()&&!vis[i][j];
    }
    void go(vector<vector<int>>& heights, vector<vector<int>>& vis, int i, int j, vector<int> path = {}) {
        if (i < 0 || j < 0 || i >= heights.size() || j >= heights[0].size() || vis[i][j] == 1)  return; 
        if (i == heights.size() - 1 && j == heights[0].size() - 1) { 
            path.push_back(heights[i][j]); 
            t = 0;
            for (int k = 1; k < path.size(); k++) {
                int a = abs(path[k] - path[k - 1]);
                t = max(t, a);
                // cout << path[k] << " ";
            }
            ans.push_back(t);
            // cout << " ::: " << t << " "<< "\n";
            return; 
        } 
        vis[i][j] = 1; 
        path.push_back(heights[i][j]); 
        if(j < heights[0].size() - 1 && !vis[i][j + 1]) {
            if(!(!ok(i, j + 2, vis)&&ok(i - 1, j + 1, vis)&&ok(i + 1, j + 1, vis))){
                go(heights, vis, i, j + 1, path); 
            }
        }
        if(i < heights.size() - 1 && !vis[i + 1][j]) {
            if(!(!ok(i + 2, j, vis)&&ok(i + 1, j - 1, vis)&&ok(i + 1, j + 1, vis))) {
                go(heights, vis, i + 1, j, path); 
            }
        }
        if(i > 0 && !vis[i - 1][j]) {
            if(!(!ok(i - 2, j, vis)&&ok(i - 1, j - 1, vis)&&ok(i - 1, j + 1, vis))) {
                go(heights, vis, i - 1, j, path); 
            }
        }
        if(j > 0 && !vis[i][j - 1]) {
            if(!(!ok(i, j - 2, vis)&&ok(i - 1, j - 1, vis)&&ok(i + 1, j - 1, vis))){
                go(heights, vis, i, j - 1, path); 
            }
        }
        path.pop_back(); 
        vis[i][j] = 0; 
    }

    int minimumEffortPath(vector<vector<int>>& heights) {
        int m = (int) heights.size(), n = (int) heights[0].size();
        vector<vector<int>> vis(m, vector<int>(n));
        go(heights, vis, 0, 0);
        return *min_element(ans.begin(), ans.end());
    }
};
Enter fullscreen mode Exit fullscreen mode

There are other programming solutions in the following repositories below. Star and watch for timely updates!

GitHub logo wingkwong / competitive-programming

🌟 My CP Journey - This repository contains CP solutions (mostly written in C++) from different OJs and contest sites 🌟

Discussion

pic
Editor guide