teleren/devto huggingface dataset:
1157. Leetcode Solution in Python3
Tags: python
Published: 2022-07-17 06:29:25

```
class MajorityChecker:

    def __init__(self, arr: List[int]):
        self.tree = [None] * (len(arr) * 4)
        self.arr = arr
        self.indexes = collections.defaultdict(list)
        
        self._build(0, 0, len(arr) - 1)
        
    def _build(self, node, start, end):
        if start == end:
            self.tree[node] = (self.arr[start], 1)
            self.indexes[self.arr[start]].append(start)
            return
        mid = (start + end) // 2
        self._build(node * 2 + 1, start, mid)
        self._build(node * 2 + 2, mid + 1, end)
        self._push_up(node)
        
    def _query(self, node, start, end, L, R):
        if L <= start and end <= R:
            return self.tree[node]
        mid = (start + end) // 2
        
        ans = None
        if L <= mid:
            ans = merge(ans, self._query(node * 2 + 1, start, mid, L, R))
        if mid < R:
            ans = merge(ans, self._query(node * 2 + 2, mid + 1, end, L, R))
        return ans
            
        
    def _push_up(self, node):
        self.tree[node] = merge(self.tree[node * 2 + 1], self.tree[node * 2 + 2])
        
        

    def query(self, left: int, right: int, threshold: int) -> int:
        candidate = self._query(0, 0, len(self.arr) - 1, left, right)
        candidate_num = candidate[0]
        
        count = self._count_between_range(candidate_num, left, right)
        if count >= threshold:
            return candidate_num
        return -1
        
    def _count_between_range(self, num, left, right):
      
        l = bisect.bisect_left(self.indexes[num], left)
        r = bisect.bisect_right(self.indexes[num], right)
        
        return r - l
        
        
def merge(pair_a, pair_b):
    if pair_a is None:
        return pair_b
    if pair_b is None:
        return pair_a
    
    if pair_a[0] == pair_b[0]:
        return (pair_a[0], pair_a[1] + pair_b[1])
    else:
        if pair_a[1] > pair_b[1]:
            return (pair_a[0], pair_a[1] - pair_b[1])
        else: 
            return (pair_b[0], pair_b[1] - pair_a[1])
        
    
```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/online-majority-element-in-subarray/
1621. Leetcode Solution in Python3
Tags: python
Published: 2022-07-17 06:39:06

```
class Solution:
    
    def numberOfSets(self, n: int, k: int) -> int:
        n = n - 1
        mod = 1e9 + 7
        dp = [[1 for _ in range(n + 1)] for _ in range(k + 1)]
        
        for i in range(1, k + 1):
            for j in range(0, n + 1):
                if j < i:
                    dp[i][j] = 0
                elif j == i:
                    dp[i][j] = 1
                else:
                    ret = 0
                    ret = (ret + dp[i][j-1]) % mod
                    ret = (ret + dp[i-1][j-1]) % mod
                    dp[i][j] = ret
            

            for x in range(n + 1):
                if x == 0:
                    continue
                else:
                    dp[i][x] = (dp[i][x] + dp[i][x-1]) % mod
        
        # print(dp)
        return int(dp[k][n])
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments/
1727. Leetcode Solution in cpp
Tags: cpp
Published: 2022-07-17 06:37:56

```
class Solution {
public:
    int largestSubmatrix(vector<vector<int>>& a) {
        int n = a.size(), m = a[0].size();
        int ans = 0;
        for (int i=0; i<n; ++i) {
            vector<int> s;
            for (int j=0; j<m; ++j) {
                a[i][j] = (a[i][j] && i>0) ? a[i-1][j]+1 : a[i][j];
                s.push_back(a[i][j]);
            }
            sort(s.begin(), s.end(), std::greater<int>());
            for (int i=0; i<m; ++i) 
                ans = max(ans, (i+1) * s[i]);
        }
        return ans;
    }
};
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/largest-submatrix-with-rearrangements/
Inserting code at the begenning of the linked list
Published: 2022-07-17 06:36:50

```
#include <stdlib.h>
#include <stdio.h>

struct Node
{
  int data;
  struct Node *next;
};
// struct Node *head;

Node *insertVal(Node *head, int data)
{
  Node *temp = (Node *)malloc(sizeof(struct Node));
  temp->data = data;
  temp->next = head;
  head = temp;
  return head;
};
void printData(Node *head)
{
  struct Node *temp = head;
  printf("List is : ");
  while (temp != NULL)
  {
    printf("%d ", temp->data);
    temp = temp->next;
  }
  printf("\n");
};
int main()
{
  Node *head = NULL;
  printf("How many numbers ? \n");
  int n, x, i;
  scanf("%d", &n);
  printf("The number that u have entered is %d", n);
  for (i = 0; i < n; i++)
  {
    printf("Enter the data for the list \n");
    scanf("%d", &x);
    head = insertVal(head, x);
    printData(head);
  }
  return 0;
}
```
2003. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-17 06:35:44

```
class Solution {
 public:
  vector<int> smallestMissingValueSubtree(vector<int>& parents,
                                          vector<int>& nums) {
    const int n = parents.size();
    vector<int> ans(n, 1);
    vector<vector<int>> graph(n);
    unordered_set<int> seen;
    int minMiss = 1;

    for (int i = 1; i < n; ++i)
      graph[parents[i]].push_back(i);

    int nodeThatsOne = getNode(nums);
    if (nodeThatsOne == -1)
      return ans;

    int u = nodeThatsOne;
    int prev = -1;  // the u that just handled

    // upward from nodeThatsOne to root u
    while (u != -1) {
      for (const int v : graph[u]) {
        if (v == prev)
          continue;
        dfs(v, graph, seen, nums);
      }
      seen.insert(nums[u]);
      while (seen.count(minMiss))
        ++minMiss;
      ans[u] = minMiss;
      prev = u;
      u = parents[u];
    }

    return ans;
  }

 private:
  int getNode(const vector<int>& nums) {
    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] == 1)
        return i;
    return -1;
  }

  void dfs(int u, const vector<vector<int>>& graph, unordered_set<int>& seen,
           const vector<int>& nums) {
    seen.insert(nums[u]);
    for (const int v : graph[u])
      dfs(v, graph, seen, nums);
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/
1928. Leetcode Solution in cpp
Tags: cpp
Published: 2022-07-17 06:33:26

```
struct T {
  int node;
  int cost;
  int time;
  T(int node, int cost, int time) : node(node), cost(cost), time(time) {}
};

class Solution {
 public:
  int minCost(int maxTime, vector<vector<int>>& edges,
              vector<int>& passingFees) {
    const int n = passingFees.size();
    vector<vector<pair<int, int>>> graph(n);
    auto compare = [](const T& a, const T& b) {
      return a.cost == b.cost ? a.time > b.time : a.cost > b.cost;
    };
    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);
    vector<int> cost(n, INT_MAX);  // cost[i] := min cost to reach cities[i]
    vector<int> time(n, INT_MAX);  // time[i] := min time to reach cities[i]

    for (const auto& e : edges) {
      const int x = e[0];
      const int y = e[1];
      const int t = e[2];
      graph[x].emplace_back(y, t);
      graph[y].emplace_back(x, t);
    }

    // start with node 0 with cost = time = 0
    minHeap.emplace(0, passingFees[0], 0);
    cost[0] = passingFees[0];
    time[0] = 0;

    while (!minHeap.empty()) {
      const auto [x, currCost, currTime] = minHeap.top();
      minHeap.pop();
      for (const auto& [y, pathTime] : graph[x]) {
        if (currTime + pathTime <= maxTime) {
          // go from x -> y
          const int newCost = currCost + passingFees[y];
          const int newTime = currTime + pathTime;
          if (cost[y] > newCost) {
            cost[y] = newCost;
            time[y] = newTime;
            minHeap.emplace(y, newCost, newTime);
          } else if (time[y] > newTime) {
            time[y] = newTime;
            minHeap.emplace(y, newCost, newTime);
          }
        }
      }
    }

    return cost.back() == INT_MAX ? -1 : cost.back();
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/
1392. Leetcode Solution in cpp
Tags: cpp
Published: 2022-07-17 06:32:02

```
class Solution {
public:
    string longestPrefix(string s) {
        // dp[i] = k: the maximum k s.t. dp[0:k-1] == dp[i-k+1, i]
        int n = s.size();
        vector<int> dp(n, 0);

        for(int i = 1; i < n; ++i) {
            int j = dp[i-1]; // j is k
            while(j >= 1 && s[j] != s[i]) {
                j = dp[j-1];
            }
            dp[i] = j + (s[i] == s[j]);
        }
        int len = dp[n-1];
        return s.substr(0, len);
    }
};
```


#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/longest-happy-prefix/
1916. Leetcode Solution in Java
Tags: java
Published: 2022-07-17 06:30:47

```
class Solution {
    static final int MODULO = 1000000007;

    public int waysToBuildRooms(int[] prevRoom) {
        int n = prevRoom.length;
        int[] degree = new int[n];
        for (int i = 0; i < n; i++) {
            if (prevRoom[i] >= 0)
                degree[prevRoom[i]]++;
        }
        int[] fac = new int[n + 1];
        Arrays.fill(fac, 1);
        int[] inv = new int[n + 1];
        Arrays.fill(inv, 1);
        for (int i = 2; i <= n; i++)
            fac[i] = (int) ((long) i * fac[i - 1] % MODULO);
        for (int i = 2; i <= n; i++)
            inv[i] = (int) power(fac[i], MODULO - 2);
        Queue<Integer> queue = new LinkedList<Integer>();
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        for (int i = 0; i < n; i++) {
            if (degree[i] == 0)
                queue.offer(i);
        }
        int[] sizes = new int[n];
        Arrays.fill(sizes, 1);
        while (!queue.isEmpty()) {
            int u = queue.poll();
            dp[u] = (int) ((long) dp[u] * fac[sizes[u] - 1] % MODULO);
            int v = prevRoom[u];
            if (v < 0)
                continue;
            sizes[v] += sizes[u];
            if (--degree[v] == 0)
                queue.offer(v);
            dp[v] = (int) ((long) dp[v] * inv[sizes[u]] % MODULO * dp[u] % MODULO);
        }
        return dp[0];
    }

    public long power(long x, int n) {
        long pow = 1;
        for (int i = n; i != 0; i /= 2) {
            if (i % 2 == 1)
                pow = pow * x % MODULO;
            x = x * x % MODULO;
        }
        return pow;
    }
}
```


#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/
675. Leetcode Solution in cpp
Tags: cpp
Published: 2022-07-17 06:25:33

```
struct T {
  int i;
  int j;
  int height;
  T(int i, int j, int height) : i(i), j(j), height(height) {}
};

class Solution {
 public:
  int cutOffTree(vector<vector<int>>& forest) {
    auto compare = [&](const T& a, const T& b) { return a.height > b.height; };
    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);

    for (int i = 0; i < forest.size(); ++i)
      for (int j = 0; j < forest[0].size(); ++j)
        if (forest[i][j] > 1)
          minHeap.emplace(i, j, forest[i][j]);

    int ans = 0;
    int x = 0;
    int y = 0;

    while (!minHeap.empty()) {
      const auto [i, j, _] = minHeap.top();
      minHeap.pop();
      // walk from (x, y) to (i, j)
      const int steps = bfs(forest, x, y, i, j);
      if (steps < 0)
        return -1;
      ans += steps;
      x = i;
      y = j;
    }

    return ans;
  }

 private:
  const vector<int> dirs{0, 1, 0, -1, 0};

  int bfs(const vector<vector<int>>& forest, int si, int sj, int ei, int ej) {
    const int m = forest.size();
    const int n = forest[0].size();
    int steps = 0;
    queue<pair<int, int>> q{{{si, sj}}};
    vector<vector<bool>> seen(m, vector<bool>(n));
    seen[si][sj] = true;

    while (!q.empty()) {
      for (int s = q.size(); s > 0; --s) {
        const auto [i, j] = q.front();
        q.pop();
        if (i == ei && j == ej)
          return steps;
        for (int k = 0; k < 4; ++k) {
          const int x = i + dirs[k];
          const int y = j + dirs[k + 1];
          if (x < 0 || x == m || y < 0 || y == n)
            continue;
          if (seen[x][y] || forest[x][y] == 0)
            continue;
          q.emplace(x, y);
          seen[x][y] = true;
        }
      }
      ++steps;
    }

    return -1;
  };
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/cut-off-trees-for-golf-event/
1238. Leetcode Solution in cpp
Tags: cpp
Published: 2022-07-17 06:11:44

```
class Solution {
 public:
  vector<int> circularPermutation(int n, int start) {
    vector<int> ans;

    for (int i = 0; i < 1 << n; ++i)
      ans.push_back(start ^ i ^ i >> 1);

    return ans;
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/circular-permutation-in-binary-representation/
1338. Leetcode Solution in cpp
Tags: cpp
Published: 2022-07-17 06:10:44

```
class Solution {
 public:
  int minSetSize(vector<int>& arr) {
    const int n = arr.size();
    int sum = 0;
    unordered_map<int, int> map;
    vector<pair<int, int>> count;

    for (const int a : arr)
      ++map[a];

    for (const auto& [a, freq] : map)
      count.push_back(make_pair(a, freq));

    sort(begin(count), end(count),
         [](const auto& a, const auto& b) { return a.second > b.second; });

    for (int i = 0; i < count.size(); ++i) {
      sum += count[i].second;
      if (sum >= n / 2)
        return i + 1;
    }

    throw;
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/reduce-array-size-to-the-half/
678. Leetcode Solution in cpp
Tags: cpp
Published: 2022-07-17 06:09:26

```
class Solution {
public:
    bool checkValidString(string s) {
        int open_count = 0, close_count =0;
        int len= s.length()-1;
        for(int i=0;i<=len;i++)
        {
            if(s[i] == '(' || s[i] == '*')
                open_count ++;
            else 
                open_count --;
            if(s[len-i] == ')' || s[len-i] == '*')
                close_count ++;
            else
                close_count --;
            if(open_count < 0 || close_count <0)
                return false;
        }
        return true;
    }
};
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/valid-parenthesis-string/
1437. Leetcode Solution in Python3
Tags: python
Published: 2022-07-17 06:07:27

```
class Solution:
  def kLengthApart(self, nums: List[int], k: int) -> bool:
    if k == 0:
      return True

    n = len(nums)

    curr = 0
    next = 1

    while curr < n and next < n:
      if nums[next] == 1:
        if nums[curr] == 1 and next - curr <= k:
          return False
        curr = next
      next += 1

    return True

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/
1413. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-17 06:06:24

```
class Solution {
public:
    int minStartValue(vector<int>& nums) {
        int cumMin = INT_MAX;
        int cumSum = 0;
        
        for(int num : nums){
            cumSum += num;
            cumMin = min(cumMin, cumSum);
        }
        
        if(cumMin > 0) return 1;
        return -cumMin + 1;
    }
};
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/
1394. Leetcode Solution in Python3
Tags: python
Published: 2022-07-17 06:04:50

```
from typing import List
import collections

class Solution:
    def findLucky(self, arr: List[int]) -> int:
        cnt = collections.Counter(arr)
    
        res = sorted(cnt.items(), key=lambda x:(x[1],x[0]), reverse=True)
        for i in range(len(res)):
            
            if res[i][0] == res[i][1]:
                return res[i][0]
        return -1

if __name__ == "__main__":
    arr = [2,2,3]
    print(Solution().findLucky(arr))
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/find-lucky-integer-in-an-array/
1047. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-17 06:02:20

```
class Solution {
 public:
  string removeDuplicates(const string& S) {
    string ans;

    for (const char c : S)
      if (!ans.empty() && ans.back() == c)
        ans.pop_back();
      else
        ans.push_back(c);

    return ans;
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/
1078. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-17 06:01:17

```
class Solution {
 public:
  vector<string> findOcurrences(string text, string first, string second) {
    vector<string> ans;
    stringstream ss(text);

    for (string prev2, prev, word; ss >> word;) {
      if (prev2 == first && prev == second)
        ans.push_back(word);
      prev2 = prev;
      prev = word;
    }

    return ans;
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/occurrences-after-bigram/
Top Software Engineering Blogs
Published: 2022-07-17 05:58:00

This is a growing collection of blogs by software companies that you can read to get Engineering practices and Software Architecture ideas.

- [Airbnb](https://medium.com/airbnb-engineering)
- [Altassian](https://blog.developer.atlassian.com/)
- [Asana](https://blog.asana.com/category/eng/)
- [BitTorrent](https://engineering.bittorrent.com/)
- [Canva](https://canvatechblog.com/)
- [Cloudera](https://blog.cloudera.com/category/technical/)
- [CLoudflare](https://blog.cloudflare.com/tag/engineering/)
- [Cred](https://engineering.cred.club/)
- [Docker](https://www.docker.com/blog/category/engineering/)
- [Dropbox](https://dropbox.tech/)
- [Dunzo](https://blog.dunzo.com/tagged/engineering)
- [eBay](https://tech.ebayinc.com/engineering/)
- [GitHub](https://github.blog/category/engineering/)
- [Groupon](https://medium.com/groupon-eng)
- [Hackerearth](http://engineering.hackerearth.com/)
- [Instagram](https://instagram-engineering.com/)
- [Intercom](https://www.intercom.com/blog/engineering/)
- [LinkedIn](https://engineering.linkedin.com/)
- [Lyft](https://eng.lyft.com/tagged/mobile)
- [Meta](https://engineering.fb.com/)
- [MixPanel](https://mixpanel.com/blog/)
- [Netflix](https://netflixtechblog.com/)
- [Nextdoor](https://engblog.nextdoor.com/)
- [Paypal](https://medium.com/paypal-tech)
- [Practo](https://medium.com/practo-engineering)
- [Quora](https://quoraengineering.quora.com/)
- [Reddit](https://www.redditinc.com/blog)
- [Salesforce](https://developer.salesforce.com/blogs)
- [Shopify](https://shopify.engineering/)
- [Slack](https://slack.engineering/)
- [Soundcloud](https://developers.soundcloud.com/blog/)
- [Spotify](https://engineering.atspotify.com/)
- [Stripe](https://stripe.com/blog/engineering)
- [Swiggy](https://bytes.swiggy.com/)
- [Thumbstack](https://medium.com/thumbtack-engineering)
- [Tumblr](https://yahooeng.tumblr.com/)
- [Twitter](https://blog.twitter.com/engineering/en_us/topics/insights)
- [Uber](https://eng.uber.com/)
- [Yelp](https://engineeringblog.yelp.com/)
- [Zerodha](https://zerodha.tech/)
- [Zomato](https://www.zomato.com/blog/category/technology)
- [Zoom](https://medium.com/zoom-developer-blog)

You can download this [Bookmarks file](https://drive.google.com/file/d/1br6haCJETLhMLRpIQZ3RCbB0qAOLea-V/view?usp=sharing) and import it into your browser.
1761. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-17 05:57:29

```
class Solution {
public:
  int minTrioDegree(int n, vector<vector<int>>& edges) {
    vector<bitset<400>> g(n);
    for (const auto& e : edges) {
      g[e[0] - 1].set(e[1] - 1);
      g[e[1] - 1].set(e[0] - 1);
    }
    size_t ans = INT_MAX;
    for (int i = 0; i < n; ++i)
      for (int j = i + 1; j < n; ++j)
        if (g[i][j])
          for (int k = j + 1; k < n; ++k)
            if (g[i][k] && g[j][k])
              ans = min(ans, g[i].count() + g[j].count() + g[k].count() - 6);
    return ans == INT_MAX ? -1 : ans;
  }
};
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/
1805. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-17 05:53:34

```
class Solution {
public:
    int numDifferentIntegers(string word) {
        word += 'a';
        set<string> s;
        string tmp;
        for (char ch : word) {
            if (isdigit(ch)) {
                tmp += ch;
            } else {
                while (tmp.length() > 1 && tmp[0] == '0') {
                    tmp = tmp.substr(1);
                }
                if (!tmp.empty()) s.insert(tmp);
               tmp = ""; 
            }
        }
        
        return s.size();
    }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/number-of-different-integers-in-a-string/
Appwrite Community Report #14
Published: 2022-07-17 05:53:04

Hello World!👋Greetings from team Appwrite!  

We are back with our weekly updates!

**TLDR;** This week we have some freshly brewed discussions, resources to learn more about Appwrite and every detail about what we have been building and fixing. 😉

--- 

## 📢  What’s new 

- **Discord 3.0** is coming! Stay tuned for having some more fun with the community! 🤩
If you haven’t joined the [channel](appwrite.io/discord) yet, this is your cue.
- Appwrite OSS Fund is running in full swing, did you show this to your maintainer friends yet? 
{% embed https://appwrite.io/oss-fund %}

---

## ✅ Issues solved

This week has been about fixing existing bugs, issues, and working on community requests. 

- Created Vonage Phone Auth Adapter
🔗[Link to PR](https://github.com/appwrite/appwrite/pull/3540)

- Fixed function usage stats
🔗[Link to PR](https://github.com/appwrite/appwrite/pull/3543)
- Fixed some complex queries (cursor+order by internal attribute) giving error 500
🔗[Link to PR](https://github.com/appwrite/appwrite/pull/3543)
- Fixed date attributes missing on database
🔗[Link to PR](https://github.com/appwrite/appwrite/pull/3535)

---

## ⚒️ What we’re currently working on

- Working on Queries Gen 2
- Implementation of Bun into Appwrite Function
- Improving Deno caching, for faster cold start

---

## 🗣 Discussions
Let’s talk about Appwrite’s queries
🔗[Join the discussion here](https://github.com/appwrite/appwrite/discussions/3545)

---

## 📘 Resources

- Indexing Appwrite Collection
{% embed https://dev.to/appwrite/how-do-i-index-my-appwrite-collection-2o4n %}
- Building a [Realtime Chat Application Using Appwrite and Angular]
(https://dev.to/appwrite/building-a-realtime-chat-application-using-angular-and-appwrite-i3o)
- Connecting to external services using webhooks in Appwrite {% embed https://www.youtube.com/watch?v=Mt9zRdRJwig %}
- Learn all about [Appwrite in 30 days](https://30days.appwrite.io/)