teleren/devto huggingface dataset:
1096. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:33:55

```
class Solution {
 public:
  vector<string> braceExpansionII(string expression) {
    return dfs(expression, 0, expression.length() - 1);
  }

 private:
  vector<string> dfs(const string& expression, int s, int e) {
    set<string> ans;
    vector<vector<string>> groups{{}};
    int layer = 0;
    int left = 0;

    for (int i = s; i <= e; ++i)
      if (expression[i] == '{' && ++layer == 1)
        left = i + 1;
      else if (expression[i] == '}' && --layer == 0)
        merge(groups, dfs(expression, left, i - 1));
      else if (expression[i] == ',' && layer == 0)
        groups.push_back({});
      else if (layer == 0)
        merge(groups, {string(1, expression[i])});

    for (const auto& group : groups)
      for (const string& word : group)
        ans.insert(word);

    return {begin(ans), end(ans)};
  }

  void merge(vector<vector<string>>& groups, const vector<string> group) {
    if (groups.back().empty()) {
      groups[groups.size() - 1] = group;
      return;
    }

    vector<string> mergedGroup;

    for (auto& word1 : groups.back())
      for (auto& word2 : group)
        mergedGroup.push_back(word1 + word2);

    groups[groups.size() - 1] = mergedGroup;
  }
};

```
1092. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:32:15

```
class Solution {
 public:
  string shortestCommonSupersequence(string str1, string str2) {
    string ans;
    int i = 0;  // str1's index
    int j = 0;  // str2's index

    for (const char c : lcs(str1, str2)) {
      // append chars that are not part of the LCS
      while (str1[i] != c)
        ans += str1[i++];
      while (str2[j] != c)
        ans += str2[j++];
      // append the char of the LCS and match str1 and str2
      ans += c;
      ++i;
      ++j;
    }

    // append remaining chars
    return ans + str1.substr(i) + str2.substr(j);
  }

 private:
  string lcs(const string& A, const string& B) {
    const int m = A.length();
    const int n = B.length();
    // dp[i][j] := LCS of A[0..i) and B[0..j)
    vector<vector<string>> dp(m + 1, vector<string>(n + 1));

    for (int i = 1; i <= m; ++i)
      for (int j = 1; j <= n; ++j)
        if (A[i - 1] == B[j - 1])
          dp[i][j] = dp[i - 1][j - 1] + A[i - 1];
        else
          dp[i][j] = dp[i - 1][j].length() > dp[i][j - 1].length()
                         ? dp[i - 1][j]
                         : dp[i][j - 1];

    return dp[m][n];
  }
};

```
1036. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:31:28

```
class Solution {
 public:
  bool isEscapePossible(vector<vector<int>>& blocked, vector<int>& source,
                        vector<int>& target) {
    unordered_set<long> blockedSet;
    for (const auto& b : blocked)
      blockedSet.insert(hash(b[0], b[1]));

    return dfs(blockedSet, source[0], source[1], hash(target[0], target[1]),
               {}) &&
           dfs(blockedSet, target[0], target[1], hash(source[0], source[1]),
               {});
  }

 private:
  bool dfs(unordered_set<long>& blockedSet, int i, int j, long target,
           unordered_set<long>&& visited) {
    if (i < 0 || i >= 1e6 || j < 0 || j >= 1e6 ||
        blockedSet.count(hash(i, j)) || visited.count(hash(i, j)))
      return false;

    visited.insert(hash(i, j));
    if (visited.size() > (1 + 199) * 199 / 2 || hash(i, j) == target)
      return true;
    return dfs(blockedSet, i + 1, j, target, move(visited)) ||
           dfs(blockedSet, i - 1, j, target, move(visited)) ||
           dfs(blockedSet, i, j + 1, target, move(visited)) ||
           dfs(blockedSet, i, j - 1, target, move(visited));
  }

  long hash(int i, int j) {
    return (static_cast<long>(i) << 16) + j;
  }
};

```
1028. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:28:29

```
class Solution {
 public:
  TreeNode* recoverFromPreorder(string S) {
    int i = 0;
    return recoverFromPreorder(S, 0, i);
  }

 private:
  TreeNode* recoverFromPreorder(const string& S, int depth, int& i) {
    int nDashes = 0;
    while (i + nDashes < S.length() && S[i + nDashes] == '-')
      ++nDashes;
    if (nDashes != depth)
      return nullptr;

    i += depth;
    const int start = i;
    while (i < S.length() && isdigit(S[i]))
      ++i;

    const int val = stoi(S.substr(start, i - start));
    TreeNode* root = new TreeNode(val);

    root->left = recoverFromPreorder(S, depth + 1, i);
    root->right = recoverFromPreorder(S, depth + 1, i);

    return root;
  }
};

```
React Starter Template
Tags: react
Published: 2022-07-03 17:27:51


{% youtube OgUUyPXXbCg %}

Features of this starter template

- Typescript, Husky, eslint configured
- Staged lint 
- Router dom with initial routes 
- CSS library Tailwind installed 
- SCSS added 
- and many more

Repo: https://github.com/itobuztech/react-starter-template

React Starter Template to enhange and speedup project development
996. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:27:18

```
// Time: O(N!)
// Space: O(N^2)
class Solution {
    int ans = 0;
    inline bool isSquare(int n) {
        int r = sqrt(n);
        return r * r == n;
    }
    void dfs(vector<int> &A, int start) {
        if (start == A.size()) {
            ++ans;
            return;
        }
        unordered_set<int> s;
        for (int i = start; i < A.size(); ++i) {
            if (s.count(A[i]) || (start - 1 >= 0 && !isSquare(A[start - 1] + A[i]))) continue;
            s.insert(A[i]);
            swap(A[start], A[i]);
            dfs(A, start + 1);
            swap(A[start], A[i]);
        }
    }
public:
    int numSquarefulPerms(vector<int>& A) {
        dfs(A, 0);
        return ans;
    }
};
```
995. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:26:20

```
class Solution {
 public:
  int minKBitFlips(vector<int>& A, int K) {
    int ans = 0;
    int flippedTime = 0;

    for (int r = 0; r < A.size(); ++r) {
      if (r >= K && A[r - K] == 2)
        --flippedTime;
      if (flippedTime % 2 == A[r]) {
        if (r + K > A.size())
          return -1;
        ++ans;
        ++flippedTime;
        A[r] = 2;
      }
    }

    return ans;
  }
};

```
Use playwright to download files from remote servers
Tags: playwright, automatedtesting, typescript, testautoma
Published: 2022-07-03 07:00:54


Downloading files from a remote server is often a challenging prospect when it comes to incorporating the process into an automated test. This task can be easily performed by using Playwrights' native REST API helper library.

The example below is a typical pseudo Download button with a `href` pointing to location of a file on a remote server.

![Typical download button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3pagx8i40mncozdpv6qu.png)
 

There are numerous ways of tackling this issue using Playwright.  Our example below will utilise Playwrights' ability to perform REST calls.

Firstly, you'll need to `fs`

```typescript
import * as fs from 'fs/promises'  // For saving the file contents to disk
```

Within your test, define the `baseUrl` and the `resource` path of the file for download.

```typescript
const baseUrl = 'https://www.tesla.com/'
const resource = 'ns_videos/2021-tesla-impact-report.pdf'
```

Simply invoke the `get` method from the API testing helper

```typescript
const getResp = await page.context().request.get(`${baseUrl}${resource}`)
```

 

The response body will be a buffer type.  We can save this raw content into a file using the standard `fs`   library.  In the example below, I opted to include a random timestamp to the downloaded file.  This is entirely optional, your implementation may vary.

```typescript
let responseBuffer = await getResp.body()
await fs.writeFile(`${new Date().valueOf()}_downloaded_pdf_from_tesla.pdf`, responseBuffer, 'binary')
```

When the test is executed, the downloaded file (pdf in this example) will appear on your local disk, like so …

![File downloaded to the root of the project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yl2fycyk8j4h2fabtuyx.png)
 

Downloading the file directly into the project root folder may not be ideal in most scenarios.  Let us make one more change to our test and output the file into a different directly.

Add `testInfo` to the test definition:

```typescript
test('able to download a remote file to disk', async ({ page }, testInfo) => {
```

Modify the download path to use the output path provided by the `testInfo` object.

```typescript
const fileName = `${new Date().valueOf()}_downloaded_pdf_from_tesla.pdf`
const downloadPath = testInfo.outputPath(fileName)
await fs.writeFile(downloadPath, responseBuffer, 'binary')
```

Rerunning the test will result in the downloaded file being persisted within the `test-results` folder:

![File saved into the test-results folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hknntutqufgunilx7l6.png)
 
### The final solution:

{% embed https://gist.github.com/ryanrosello-og/f9700c548a405367d6642ed09d4e7b16.js %}
992. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:25:36

```
class Solution {
public:
    int subarraysWithKDistinct(vector<int>& A, int K) {
        int ans = 0, i = 0, j = 0, k = 0, N = A.size();
        unordered_map<int, int> m;
        while (j < N) {
            m[A[j] - '0'] = j;
            ++j;
            while (m.size() > K) {
                int d = A[i++] - '0';
                if (m[d] < i) m.erase(d);
            }
            if (m.size() == K) {
                k = max(i, k);
                while (m[A[k] - '0'] != k) ++k;
                ans += k - i + 1;
            }
        }
        return ans;
    }
};

```
982. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:24:36

```
class Solution {
 public:
  int countTriplets(vector<int>& A) {
    constexpr int kMax = 1 << 16;
    int ans = 0;
    vector<int> count(kMax);  // {A[i] & A[j]: times}

    for (const int a : A)
      for (const int b : A)
        ++count[a & b];

    for (const int a : A)
      for (int i = 0; i < kMax; ++i)
        if (!(a & i))
          ans += count[i];

    return ans;
  }
};

```
975. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:23:51

```
class Solution {
 public:
  int oddEvenJumps(vector<int>& A) {
    const int n = A.size();
    map<int, int> map;    // {num: min index}
    vector<bool> inc(n);  // inc[i] := can reach A[n - 1] from i w/ inc jump
    vector<bool> dec(n);  // dec[i] := can reach A[n - 1] from i w/ dec jump

    map[A[n - 1]] = n - 1;
    inc.back() = true;
    dec.back() = true;

    for (int i = n - 2; i >= 0; --i) {
      const auto lo = map.lower_bound(A[i]);  // min val >= A[i]
      const auto hi = map.upper_bound(A[i]);  // min val > A[i]
      if (lo != cend(map))
        inc[i] = dec[lo->second];
      if (hi != cbegin(map))
        dec[i] = inc[prev(hi)->second];
      map[A[i]] = i;
    }

    return count(begin(inc), end(inc), true);
  }
};

```
964. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:21:55

```
class Solution {
 public:
  int leastOpsExpressTarget(int x, int target) {
    return dfs(x, target, {});
  }

 private:
  int dfs(int x, int target, unordered_map<int, int>&& memo) {
    if (memo.count(target))
      return memo[target];
    if (x > target)
      return min(2 * target - 1, 2 * (x - target));
    if (x == target)
      return 0;

    long prod = x;
    int n = 0;
    while (prod < target) {
      prod *= x;
      ++n;
    }
    if (prod == target)
      return memo[target] = n;

    int ans = dfs(x, target - prod / x, move(memo)) + n;
    if (prod < 2 * target)
      ans = min(ans, dfs(x, prod - target, move(memo)) + n + 1);
    return memo[target] = ans;
  }
};

```
1335. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:20:38

```
class Solution {
 public:
  int minDifficulty(vector<int>& jobDifficulty, int d) {
    const int n = jobDifficulty.size();
    if (n < d)
      return -1;

    // dp[i][k] := min difficulty to schedule the first i jobs in k days
    vector<vector<int>> dp(n + 1, vector<int>(d + 1, INT_MAX / 2));
    dp[0][0] = 0;

    for (int i = 1; i <= n; ++i)
      for (int k = 1; k <= d; ++k) {
        int maxDifficulty = 0;                  // max(job[j + 1..i])
        for (int j = i - 1; j >= k - 1; --j) {  // 1-based
          maxDifficulty = max(maxDifficulty, jobDifficulty[j]);  // 0-based
          dp[i][k] = min(dp[i][k], dp[j][k - 1] + maxDifficulty);
        }
      }

    return dp[n][d];
  }
};

```
1326. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:19:46

```
class Solution {
 public:
  int minTaps(int n, vector<int>& ranges) {
    vector<int> nums(n + 1);

    for (int i = 0; i <= n; ++i) {
      int l = max(0, i - ranges[i]);
      int r = min(n, i + ranges[i]);
      nums[l] = max(nums[l], r - l);
    }

    int ans = 0;
    int end = 0;
    int farthest = 0;

    for (int i = 0; i < n; i++) {
      farthest = max(farthest, i + nums[i]);
      if (i == end) {
        ++ans;
        end = farthest;
      }
    }

    return end == n ? ans : -1;
  }
};

```
The pitfall of tutorials: no one codes like that
Tags: beginners, programming, tutorial, productivity
Published: 2022-07-03 17:19:27

TDLR: Refactor, refactor, refactor!

---

So, you want to learn some new language or framework, you find a tutorial and it takes you step by step.

First you start at `A` then, of course, `B` to the “logical” jump to `C` to finish with `D`.

All elegant and logical, one point to another with all the steps you didn’t even consider you would need, done by the time you need then.

Just like when you actually have to do something right?

## Programming is “dirty” work

In the short time they have to get you to watch the tutorial, they have to be neat and to the point.

But don’t kid yourself. That’s just the finished version after countless rounds of refactoring.

Even the best programmers out there first make a mess only to refactor and give you the neat version.

## The pitfall of not refactoring

People who only go by the tutorial and think that IS programming end up thinking that, they too, just like the tutorial can make those complex jumps in logic and that their “finished” product is as easy as `A -> B -> C -> D` except it’s far from the truth.

They do something like: `A -> Z -> J -> G -> Z -> C -> P -> O -> D` repeating some steps, making a roundabout way instead of a neat alternative, finish and call it a day!

### TDD

If you’re learned about TDD then you know the 3 steps:

- Red: test don’t pass
- Green: make tests pass
- Refactor!

Even if you don’t use tests, you can still make use of those three steps:

- It doesn’t work.
- It works.
- Refactor!

### Refactoring is like “washing your hands”

Uncle Bob says that making tests and refactoring are some things that are like washing your hands if you’re a surgeon. You don’t need to put it on the calendar, or maybe block a whole week of the month just for that.

It’s something that you just do! It’s expected to be part of any estimate you have.

It’s something you simply cannot afford not to do.

### The “boy scout rule”

The best time to refactor was when you made the mess, the next best time is now!

Every time you change something in the code is an opportunity to improve it.

So… every time you check out a file: refactor it!

## Refactor, Refactor, Refactor!

It’s never gonna be enough, and that’s ok!

Every time you see the code you’ve made and what you could do now will show your progress.

### How to start?

Now… this is a story for another time.

In the meantime, search for: Kent Beck, Martin Fowler, Michael Feathers, Sandi Metz, and Uncle Bob.

---

Cover Photo by [Markus Winkler](https://unsplash.com/@markuswinkler?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/tutorial?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
1330. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:17:23

```
class Solution {
public:
    int maxValueAfterReverse(vector<int>& A) {
        if (A.size() == 2) return abs(A[0] - A[1]);
        int ans = 0, N = A.size(), maxGap = 0, low = max(A[0], A[1]), high = min(A[0], A[1]);
        for (int i = 1; i < N; ++i) ans += abs(A[i] - A[i - 1]);
        for (int i = 3; i < N; ++i) {
            maxGap = max({ maxGap, high - max(A[i - 1], A[i]), min(A[i - 1], A[i]) - low });
            high = max(high, min(A[i - 2], A[i - 1]));
            low = min(low, max(A[i - 2], A[i - 1]));
        }
        maxGap *= 2;
        for (int i = 0; i < N - 2; ++i) maxGap = max(maxGap, abs(A[N - 1] - A[i]) - abs(A[i + 1] - A[i]));
        for (int i = 2; i < N; ++i) maxGap = max(maxGap, abs(A[0] - A[i]) - abs(A[i] - A[i - 1]));
        return ans + maxGap;
    }
};
```
New VR Soundscapes API
Tags: vr, audio, api, soundscape
Published: 2022-07-03 17:16:56

## Every space deserves a soundscape
{% embed https://soundcloud.com/soundscape-city/morning-in-vr-nature %}
Until now, the developer has to obtain and manage the audio, choosing the exact sounds that will never be changed or updated in that specific situation.

Now, any developer can send a simple GET request with an API key, asking for a 'late-night' soundscape during a weather storm, or early-morning jungle next to a lake soundscape and get it immediately. 

It will change the VR & AR development industry as it can be used on any development platform like Unity, Maya, Unreal, KeyShot, Blender, and more.
Any platform that allows the developer to use a GET request is supported.

**The early adopter's free account gives you 1,000,000 requests per month at 1,000 requests per second and 50 bursts.**

[Detailed API Docs are here](https://www.soundscape.city/documentation.html)

## Infinite Soundscapes
The soundscapes are infinite and seamlessly loopable, they are created daily by the thousands for many VR situations, even the same api call will return a new soundscape every time you use it.

## No Royalties
SSC own 100% of the sounds that the engine creates, so once you're subscribed, you pay $0 for royalties of any kind, no matter if you have 100 or 100,000,000 active users.

## Reliable & Secure
SSC uses the most secure and reliable infrastructure, your apps and games soundscapes are safe and no data collection is being done on your users or app/game.

{% embed https://soundcloud.com/soundscape-city/star-gazing %}

#So What Are The API Main Features?
## Weather
Provides the user with incredible weather soundscapes for various types of rain, winds, thunder, and more.

## Menus
Make the audio experience amazing with an intelligent menu feature for spooky, calm, inspirational, or dark menus.

## Time Of Day
Let the user immerse into your app or game with sensitive time of day soundscapes, like early morning, late morning, noon, afternoon, evening or night.

## Environment
Change soundscapes while moving between different environments like apartments, caves, deserts, forests, jungles, lakes, outer space, underwater, and more.

Signup for free now at:
https://soundscape.city

Enjoy!
1316. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:15:47

```
class Solution {
public:
    int distinctEchoSubstrings(string s) {
        int N = s.size(), mod = 1e8 + 7, cnt = 0;
        vector<long> v(N);
        for (int len = 1; len <= N / 2; ++len) {
            long hash = s[0] - 'a', p = 1;
            unordered_set<string> seen;
            for (int i = 1; i < N; ++i) {
                if (i < len) {
                    hash = (hash * 26 + s[i] - 'a') % mod;
                    p = (p * 26) % mod;
                } else {
                    hash = ((hash - (s[i - len] - 'a') * p) * 26 + s[i] - 'a') % mod;
                    if (hash < 0) hash += mod;
                    if (i - 2 * len + 1 >= 0 && v[i - len] == hash) {
                        auto a = s.substr(i - 2 * len + 1, len);
                        if (seen.count(a)) continue;
                        seen.insert(a);
                        if (a == s.substr(i - len + 1, len)) ++cnt;
                    }
                }
                v[i] = hash;
            }
        }
        return cnt;
    }
};
```
1301. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:13:01

```

// Time: O(MN)
// Space: O(N)
class Solution {
    const int mod = 1e9 + 7;
public:
    vector<int> pathsWithMaxScore(vector<string>& A) {
        int M = A.size(), N = A[0].size();
        vector<int> zero(2, 0);
        vector<vector<vector<int>>> dp(2, vector<vector<int>>(N, vector<int>(2, 0)));
        dp[(M - 1) % 2][N - 1][1] = 1;
        for (int i = M - 1; i >= 0; --i) {
            for (int j = N - 1; j >= 0; --j) {
                if (A[i][j] == 'S') dp[i % 2][j] = { 0, 1 };
                else if (A[i][j] == 'X') dp[i % 2][j] = zero;
                else {
                    int sum = 0, cnt = 0;
                    auto &B = i + 1 < M ? dp[(i + 1) % 2][j] : zero;
                    auto &R = j + 1 < N ? dp[i % 2][j + 1] : zero;
                    auto &BR = i + 1 < M && j + 1 < N ? dp[(i + 1) % 2][j + 1] : zero;
                    sum = max({ B[0], R[0], BR[0] });
                    if (B[0] == sum) cnt = (cnt + B[1]) % mod;
                    if (R[0] == sum) cnt = (cnt + R[1]) % mod;
                    if (BR[0] == sum) cnt = (cnt + BR[1]) % mod;
                    dp[i % 2][j] = { sum, cnt };
                }
                if (dp[i % 2][j][1] && isdigit(A[i][j])) dp[i % 2][j][0] += A[i][j] - '0';
            }
        }
        return dp[0][0];
    }
};
```
1278. Leetcode Soluiton in Cpp
Tags: cpp
Published: 2022-07-03 17:11:42

```
class Solution {
 public:
  int palindromePartition(string s, int k) {
    const int n = s.length();
    // dp[i][k] := min cost to make k palindromes by s[0..i)
    dp.resize(n + 1, vector<int>(k + 1, n));
    // cost[i][j] := min cost to make s[i..j] palindrome
    cost.resize(n, vector<int>(n));

    for (int d = 1; d < n; ++d)
      for (int i = 0, j = d; j < n; ++i, ++j)
        cost[i][j] = (s[i] != s[j]) + cost[i + 1][j - 1];

    return palindromePartition(n, k);
  }

 private:
  vector<vector<int>> dp;
  vector<vector<int>> cost;

  int palindromePartition(int n, int k) {
    if (k == 1)
      return cost[0][n - 1];
    int& ans = dp[n][k];
    if (ans < n)
      return ans;

    // try all possible partitions
    for (int i = k - 1; i < n; ++i)
      ans = min(ans, palindromePartition(i, k - 1) + cost[i][n - 1]);

    return ans;
  }
};

```
1340. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-03 17:10:41

```

// Time: O(ND)
// Space: O(N)
class Solution {
    int N, D;
    vector<int> v;
    int dfs(vector<int>& arr, int start) {
        if (v[start] > 0) return v[start];
        int left = 0, right = 0;
        for (int d = 1; d <= D && start - d >= 0 && arr[start - d] < arr[start]; ++d)
            left = max(left, dfs(arr, start - d));
        for (int d = 1; d <= D && start + d < N && arr[start + d] < arr[start]; ++d)
            right = max(right, dfs(arr, start + d));
        return v[start] = 1 + max(left, right);
    }
public:
    int maxJumps(vector<int>& arr, int d) {
        N = arr.size(), D = d;
        v = vector<int>(N, 0);
        for (int i = 0; i < N; ++i) dfs(arr, i);
        int ans = 0;
        for (int i = 0; i < N; ++i) ans = max(ans, v[i]);
        return ans;
    }
};
```