loading...

Daily Coding Challenge #66

wingkwong profile image Wing-Kam ・3 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.


/*
LeetCode - Reverse Words in a String

Given an input string, reverse the string word by word.

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"
Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.


Note:

A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.

*/

class Solution {
public:
    string reverseWords(string s) {
        // use istringstream to read the words
        istringstream iss(s);
        string st,ans;
        // reverse it
        while(iss>>st) ans=st + " " + ans;
        // remove the last space
        return ans.substr(0,ans.size()-1);
    }
};

/*
LeetCode - Perfect Squares

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

Example 1:

Input: n = 12
Output: 3 
Explanation: 12 = 4 + 4 + 4.
Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
*/

class Solution {
public:
    int numSquares(int n) {
        if(n==0) return 0;
        vector<int> dp(n+1,0);
        for(int i=1;i<=n;i++){
            // i is the upper limit
            dp[i]=i;
            for(int j=1;j*j<=i;j++){
                // dp[i] means how mnay perfect square numbers which sum to i 
                // either the current dp[i] or the previous one + 1
                dp[i]=min(dp[i],dp[i-j*j]+1);
            }
        }
        return dp[n];
    }
};

/*
Path with Maximum Probability

You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].

Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.

If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.

Example 1:

Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
Output: 0.25000
Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.

Example 2:

Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
Output: 0.30000

Example 3:

Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
Output: 0.00000
Explanation: There is no path between 0 and 2.


Constraints:

2 <= n <= 10^4
0 <= start, end < n
start != end
0 <= a, b < n
a != b
0 <= succProb.length == edges.length <= 2*10^4
0 <= succProb[i] <= 1
There is at most one edge between every two nodes.
*/

class Solution {
public:
    double maxProbability(int n, vector<vector<int>>& edges, vector<double>& succProb, int start, int end) {
        // bfs approach
        vector<vector<pair<int,double>>> g(n);
        vector<double> p(n);
        vector<int> q={start};
        // build the graph
        for(int i=0;i<edges.size();i++){
            if(succProb[i]!=0){
                // bi-directional 
                // g[from].push_back(to,prob)
                g[edges[i][0]].push_back({edges[i][1],succProb[i]});
                g[edges[i][1]].push_back({edges[i][0],succProb[i]});
            }
        }
        p[start]=1;
        while(!q.empty()){
            // tmp queue
            vector<int> tmp;
            // traverse each 'from' node
            for(auto from:q){
                for(auto [to, prob]:g[from]){
                    // if p[to] is less than p[from]*prob, update p[to]
                    if(p[to]<p[from]*prob){
                        p[to]=p[from]*prob;
                        tmp.emplace_back(to);
                    }
                }
            }
            // swap them to continue
            swap(q,tmp);
        }
        return p[end];
    }
};

The source code is available in corresponding repo below. Star and watch for timely updates!

GitHub logo wingkwong / leetcode

🏆 A Collection of my LeetCode Solutions with Explanations 🏆

GitHub logo wingkwong / hackerrank

🏆 A Collection of my HackerRank Solutions with Explanations 🏆

GitHub logo wingkwong / codeforces

🏆 A Collection of my Codeforces Solutions with Explanations 🏆

GitHub logo wingkwong / atcoder

🏆 A Collection of my AtCoder Solutions with Explanations 🏆

Posted on by:

wingkwong profile

Wing-Kam

@wingkwong

Consultant by day. Developer by night. AWS certified. Exploring #CloudNative currently.

Discussion

markdown guide