teleren/devto huggingface dataset:
Is Graph Bipartite?
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 04:30:41

There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, there is an undirected edge between node `u` and node `v`. The graph has the following properties:

*   There are no self-edges (`graph[u]` does not contain `u`).
*   There are no parallel edges (`graph[u]` does not contain duplicate values).
*   If `v` is in `graph[u]`, then `u` is in `graph[v]` (the graph is undirected).
*   The graph may not be connected, meaning there may be two nodes `u` and `v` such that there is no path between them.

A graph is **bipartite** if the nodes can be partitioned into two independent sets `A` and `B` such that **every** edge in the graph connects a node in set `A` and a node in set `B`.

Return `true` _if and only if it is **bipartite**_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/10/21/bi2.jpg)

**Input:** graph = \[\[1,2,3\],\[0,2\],\[0,1,3\],\[0,2\]\]
**Output:** false
**Explanation:** There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/10/21/bi1.jpg)

**Input:** graph = \[\[1,3\],\[0,2\],\[1,3\],\[0,2\]\]
**Output:** true
**Explanation:** We can partition the nodes into two sets: {0, 2} and {1, 3}.

**Constraints:**

*   `graph.length == n`
*   `1 <= n <= 100`
*   `0 <= graph[u].length < n`
*   `0 <= graph[u][i] <= n - 1`
*   `graph[u]` does not contain `u`.
*   All the values of `graph[u]` are **unique**.
*   If `graph[u]` contains `v`, then `graph[v]` contains `u`.

**SOLUTION:**

    class Solution:
        def DFS(self, graph, curr, visited, colors):
            for j in graph[curr]:
                if j not in visited:
                    visited.add(j)
                    colors[j] = not colors[curr]
                    if not self.DFS(graph, j, visited, colors):
                        return False
                else:
                    if colors[j] == colors[curr]:
                        return False
            return True
        
        def isBipartite(self, graph: List[List[int]]) -> bool:
            n = len(graph)
            for i in range(n):
                colors = [False for node in graph]
                visited = {i}
                if not self.DFS(graph, i, visited, colors):
                    return False
            return True
Forum Prediksi Togel
Tags: prediksitogel, bocorantogel, togelhk
Published: 2022-06-06 04:29:31

Salah satu cara agar bisa mendapatkan kemenangan, yaitu dengan kalian menyimak hasil [prediksi togel](shorturl.at/fEHJX) sekarang ini juga.

Ya, sebagai salah seorang yang sangat suka dengan permainan toto online, maka kalian ingin mendapatkan kemenangan yaitu hal yang diinginkan oleh kalian semua.

Namun tidak jarang diantara pemain toto online sekarang ini, sering mengalami kekalahan atau angka yang di tebak tidak keluar.

Maka dari itu, kami pun ingin memberikan sebuah solusinya kepada kalian, dengan cara memberikan hasil dari prediksi toto macau 6 juni 2022.

Hal ini bertujuan, agar nantinya kalian bisa menebak angka dengan sangat benar, dan dapat memenangkan hasil tebakan dengan mendapatkan uang.

Jadi buat kalian yang ingin mengetahui hasil dari prediksinya, maka kalian dapat bisa menyimak semua ulasan berikut ini sekarang juga.

Hasil prediksi yang kami berikan kali ini, tentunya telah melewati tindakan prediksi yang dilakukan dengan sangat teliti.

Sumber : [Forum PRediksi](https://rwblog.id/)
LeetCode : Jewels and Stones With Solutions
Tags: java, python, webdev, programming
Published: 2022-06-06 04:28:38

Hey🖐 DevCommunity Checkout The blog for solutions above Leetcode problem statement

##Problem Statement

You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so "a" is considered a different type of stone from "A".

 

Example 1:
```
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
```
Example 2:
```
Input: jewels = "z", stones = "ZZ"
Output: 0
```

Constraints:

- 1 <= jewels.length, stones.length <= 50
- jewels and stones consist of only English letters.
- All the characters of jewels are unique.

##Solution
```
class Solution {
    public int numJewelsInStones(String jewels, String stones) {
         int count= 0;
        for (char jewel:jewels.toCharArray()) {
            for (char stone:stones.toCharArray()) {
                if(jewel==stone){
                    count++;
                }
            }

        }
        return count;
    }
}
```

###Conclusion
In this article, we learned way to solve LeetCode Problem Statement Jewels and Stones using java.

**Checkout More about Me by visiting on below links**

[Github:- Rohan2596 ](https://github.com/Rohan2596)
[Website:- kadamrohan.com ](https://kadamrohan.com/ "https://kadamrohan.com/")
[Blogs:- rohankadam965.medium.com](https://rohankadam965.medium.com/ "https://rohankadam965.medium.com/")
[Instagram:- rohankadam_codes ](https://www.instagram.com/rohankadam_codes/)

Thank You For Reading.Do like ❤ Share and Follow for more content like this.
Also share feedbacks and Solution in the comment section below
ON THE GRID
Published: 2022-06-06 04:13:46

This weeks learning goal was to work on some algorithms to grow my problem solving skills and to work on little projects with a focus on developing a skill. 

##The Project
This week I decided to try a calculator in react. Since I have heard of this coming up often as a beginner friendly project. Once again CSS grid is in the mix. I can honestly say I am enjoying this learning process. 

Let start with the basic. 

## What is CSS Grid.  
To put it simply. It is a systems of columns and rows used to build different layouts and segments of a web page. 


![CSS Grid Layout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2lpbnr26gxa2xgh19i0e.jpeg) 

In the picture above we can get just an idea of what outlines we can build with this tool. 

## Calculator Grid 

![calculator photo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hc2he9tzgub0m7rse82d.jpeg)

In the photo above we can see. Our buttons are line up in columns and row and our = button is spanning across the button on the bottom row. 


![calculator photo 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqqjst1vmdvxsix2cnka.png)

In this layout we have our C and 0 span across multipole rows


![calculator photo 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70mdedqshn1lj6qkw6lb.png)

In this layout we see our AC, 0, and = button all change in size and design. 

While all of these calculators function the same. CSS grid allows us to build and customize the look and design. 
To our liking. 

I hope you attempt CSS Grid. Having the freedom to create columns rows, and where we want things to go before we adding the functionality to them is one of the most enjoyable parts of coding.

I hope this helps peak your curiosity and you learn and experiment with CSS grid as well and as always happy coding. 

👨🏿‍💻👨🏻‍💻👩🏾‍💻👨🏻‍💻
Quick sort vs. Insertion sort
Tags: javascript, algorithms
Published: 2022-06-06 04:05:06

Here is a video of a fistfight between a quick sort that wants to sort in ascending order and an insertion sort that wants to sort in descending order.

<img width="100%" style="width:100%" src="https://raw.githubusercontent.com/abagames/sort-war/master/docs/screenshots/quick_insertion.gif">

See below for code and live demo.

{% embed https://github.com/abagames/sort-war %}

I created the sort war because I wanted to do some code-battling on sorting algorithms. The left (red) code fights to sort in ascending order, and the right (blue) code fights to sort in descending order. If they are aligned in ascending order, the left side wins. If they are aligned in descending order, the right side wins.

The code is written as ordinary JavaScript. There are two special functions.

- `get(i)`: get the i-th element from an array
- `swap(i, j)`: swaps the i-th and j-th elements of an array

You can't do `set`. If you allow `set`, you can cheat by copying the array into memory in the code, sorting it, and then writing it all at once.

The `get` instruction in the code on the right descending side returns the negative value of the element, so the code on the right side can also be written to sort the array in ascending order.

The code is executed alternately on the left and the right, using JS-Interpreter's `step()` to execute the instructions in the code.

{% embed https://github.com/NeilFraser/JS-Interpreter %}

Code that is fast to execute and can `swap` arrays frequently is strong. The speed depends on the execution unit of `step()` of the JS-Interpreter, but the more compact the code is, the faster it is.

The code size of the insertion sort is significantly more compact than the quick sort. Therefore, when the array's length is about 10, it often overwhelms and wins over quick sort by its execution speed. As arrays get longer, quick sort is considered to win.

The sorting algorithm does not assume that other algorithms will manipulate the array. Therefore, it is assumed that the array is not sorted when the execution finishes. Thus, the code runs again after its execution is completed. Quick sort can also cause errors because the array is manipulated externally, manipulating ranges beyond the array's bounds. In such cases, the code will be re-executed.

But is this a proper code-battling game? It seems to lack interest based on trilemma, such as one particular algorithm being strong against another algorithm but weak against another. It would be interesting to see a special sorting algorithm for battling with a defensive mechanism, such as actively disrupting the array if it seems aligned in the opponent's direction. However, it is doubtful that such a mechanism can be incorporated into the code of sort war.
Count Elements With Strictly Smaller and Greater Elements
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 04:00:47

Given an integer array `nums`, return _the number of elements that have **both** a strictly smaller and a strictly greater element appear in_ `nums`.

**Example 1:**

**Input:** nums = \[11,7,2,15\]
**Output:** 2
**Explanation:** The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.
Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it.
In total there are 2 elements having both a strictly smaller and a strictly greater element appear in `nums`.

**Example 2:**

**Input:** nums = \[-3,3,3,90\]
**Output:** 2
**Explanation:** The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.
Since there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in `nums`.

**Constraints:**

*   `1 <= nums.length <= 100`
*   `-105 <= nums[i] <= 105`

**SOLUTION:**

    class Solution:
        def countElements(self, nums: List[int]) -> int:
            sm = min(nums)
            mx = max(nums)
            return len([num for num in nums if num > sm and num < mx])
Ethernaut系列-Level 21(Shop)
Published: 2022-06-06 03:38:28

## LEVEL 21 （Shop）:
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

interface Buyer {
  function price() external view returns (uint);
}

contract Shop {
  uint public price = 100;
  bool public isSold;

  function buy() public {
    Buyer _buyer = Buyer(msg.sender);

    if (_buyer.price() >= price && !isSold) {
      isSold = true;
      price = _buyer.price();
    }
  }
}
```
## 通关要求
   isSold = true
   price < 100 

##要点
  view方法的限制,不能修改状态如：storage
https://docs.soliditylang.org/en/v0.8.14/contracts.html?highlight=%20view%20method#view-functions

##解题思路
跟11关思路差不多，但增加了view限制，由于不能修改storage，但需要两次返回不一定的结果，这里可以通过gasleft来判断并返回不一样的值，但这里可以使用更简单的方法如调用外部shop.isSold(这个是方法是view,是可以调用的)
如
```solidity
  function run(address _runAddress) external payable {
    ILevel(_runAddress).buy();
  } 

  function price() external view returns (uint) {
    // view不能写storage，但可以调用外部的view
    // 也可以调用gasleft()来达到两次返回不一样的值，但比较麻烦
    return ILevel(msg.sender).isSold() ? 0 : 100;
  } 
```
Count of Matches in Tournament
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 03:30:39

You are given an integer `n`, the number of teams in a tournament that has strange rules:

*   If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round.
*   If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round.

Return _the number of matches played in the tournament until a winner is decided._

**Example 1:**

**Input:** n = 7
**Output:** 6
**Explanation:** Details of the tournament: 
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.

**Example 2:**

**Input:** n = 14
**Output:** 13
**Explanation:** Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.

**Constraints:**

*   `1 <= n <= 200`

**SOLUTION:**

    class Solution:
        def numberOfMatches(self, n: int) -> int:
            matches = 0
            while n > 1:
                if n % 2 == 1:
                    matches += (n - 1) // 2
                    n = 1 + (n - 1) // 2
                else:
                    matches += n // 2
                    n = n // 2
            return matches
If programming languages were musical instruments
Tags: webdev, programming, jokes
Published: 2022-06-06 03:30:28

Perl
Notation software

Assembly
Sound Samples

C
Scripting sounds

C++
Virtual instruments

C#
Carbon fiber piano

JavaScript
Electone keyboard

TypeScript
Launchpad controller

Java
Organ

Go
Professional keyboard

PHP
Grand Piano

Ruby
Hybrid grand piano

Python
Upright piano

Rust
Workstation keyboard

Swift
Mobile app DAW

Zig
Sythesizer

Crystal
Crystal piano
Binary Search
Tags: dsa, java, algorithms, search
Published: 2022-06-06 03:09:48

* As we saw previously, we looked at the linear search and how it is able to find a target element by iterating over each and every element in the array 


* Well, binary search is the second most fundamental search algorithm after linear search. 

**NB:** While in linear search we have to find each element from an array by checking each and every element of this array. This means we have to continue iterating over every element until we find the element we are searching for or until we have reached the dead-end of the array.

#### Algorithm:
```
    arr = [2, 4, 6, 9, 11, 12, 14, 20, 36, 48] (Sorted array)
    target = 36
1. Find the middle element
2. Check:
    If target > middle => search in right else => search in left
3. if target == middle => we found element
```

**Example:**

![Binary Search Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j0z3dnf26g4rhzhurq11.png)

Here, the space in which we are searching is getting divided into spaces.

####Time complexity:
Best case: O(1)
Worst case: O(logn)


####Explanation: find the maximum number of comparisons 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ilwr4zznxn4y2mj7dm0.png)


####=> Order agnostic Binary search

* Let's say if we don't know that the array is sorted in ascending or descending order.

    arr = [90, 75, 18, 12, 6, 4, 3, 1]
    target = 75

Here, target > middle => search in left

Here, start > end -> Descending order
       90 > 1
when start < end -> Ascending order


For further explanation about Binary search algorithm, kindly check out this wonderful toturial.
[Binary Search in Java](https://www.youtube.com/watch?v=enI_KyGLYPo) by *Kunal Kushwaha*


Feel free to connect with me on [github](https://github.com/rukundob451) and [Linkedin](https://www.linkedin.com/in/benjamin-rukundo-539ab01a6/), thank you.
Network Delay Time
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 03:00:47

You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.

We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/05/23/931_example_1.png)

**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2

**Example 2:**

**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1

**Example 3:**

**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1

**Constraints:**

*   `1 <= k <= n <= 100`
*   `1 <= times.length <= 6000`
*   `times[i].length == 3`
*   `1 <= ui, vi <= n`
*   `ui != vi`
*   `0 <= wi <= 100`
*   All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.)

**SOLUTION:**

    class Solution:
        def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
            dist = [float('inf')] * n
            dist[k - 1] = 0
            for i in range(n - 1):
                for a, b, d in times:
                    if dist[b - 1] > dist[a - 1] + d:
                        dist[b - 1] = dist[a - 1] + d
            delay = max(dist)
            if delay == float('inf'):
                return -1
            return delay
Typescript Odd Number Type
Tags: webdev, typescript, programming, tutorial
Published: 2022-06-06 02:56:48

Most people: No, you cannot create an odd number type with Typescript

Meanwhile me:

```ts
type OddNumber<
    X extends number,
    Y extends unknown[] = [1],
    Z extends number = never
> = Y['length'] extends X
    ? Z | Y['length']
    : OddNumber<X, [1, 1, ...Y], Z | Y['length']>

type a = OddNumber<1> // 1 
type b = OddNumber<3> // 1 | 3
type c = OddNumber<5> // 1 | 3 | 5
type d = OddNumber<7> // 1 | 3 | 5 | 7
```

[playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gJnAcgVwLYCMICcA8BYAKAEgANKCAD2AgDs4BnKGtTLAGkKIE1yraGoyGgGsaAewDuNANoBdKAF4o0gIyyOxAFq9qdRswzZFTCADdshAHzGu0gOQAbWgHNgACzvzKugSU4B+KG0AHyhbRxd3T04ALlgEFENcEjZlFVT0qAA6HK51IKhQ8KcaVw9ZS0JCUEgoAENjeCQWbBwVawB6DqgVKGrwaHRGhJbcAGZO7t7Qsf7agGNh5qScAFZJnsKoMa3Vueg4JcTWHAB2Dent3a3ToA)

with some limitations, the input must an odd number, and cannot exceed 1999 (maximum depth of typescript recursion is only 1000)

you can do even number type using similar logic
Have you ever dealt with the performance problems on front end and how did you fix it?
Published: 2022-06-06 02:41:16

I have dealt with performance problems while working on a specific project.
It is a large-scale startup project based on React.js library.
As the project scale grew, the loading and action reacting speed became slow and it laid out a very important problem for releasing the project.
Firstly, I focused on refactoring the code for fixing the unnecessary rendering of components.
So I made useEffect hooks to separate to have the only necessary dependencies and made the components to PureComponents as possible.
Next, I reduced the bundle size of the project using the webpack bundle analyzer plugin.
Finally, the speed was improved by 70%.

Have you had the other experience related with performance problem?
Longest Subarray of 1's After Deleting One Element
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 02:30:41

Given a binary array `nums`, you should delete one element from it.

Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray.

**Example 1:**

**Input:** nums = \[1,1,0,1\]
**Output:** 3
**Explanation:** After deleting the number in position 2, \[1,1,1\] contains 3 numbers with value of 1's.

**Example 2:**

**Input:** nums = \[0,1,1,1,0,1,1,0,1\]
**Output:** 5
**Explanation:** After deleting the number in position 4, \[0,1,1,1,1,1,0,1\] longest subarray with value of 1's is \[1,1,1,1,1\].

**Example 3:**

**Input:** nums = \[1,1,1\]
**Output:** 2
**Explanation:** You must delete one element.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `nums[i]` is either `0` or `1`.

**SOLUTION:**

    class Solution:
        def longestSubarray(self, nums: List[int]) -> int:
            n = len(nums)
            chunks = []
            i = 0
            zeroFound = False
            mlen = 0
            msingle = 0
            while i < n:
                ctr = 1
                while i < n - 1 and nums[i] == nums[i + 1]:
                    ctr += 1
                    i += 1
                i += 1
                chunks.append((nums[i - 1], ctr))
                if nums[i - 1] == 1:
                    msingle = max(msingle, ctr)
                else:
                    zeroFound = True
            k = len(chunks)
            for i in range(1, k - 1):
                if chunks[i] == (0, 1):
                    mlen = max(mlen, chunks[i - 1][1] + chunks[i + 1][1])
            if zeroFound:
                mlen = max(mlen, msingle)
            else:
                mlen = max(mlen, msingle - 1)
            return mlen
Third Maximum Number
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 02:00:47

Given an integer array `nums`, return _the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number_.

**Example 1:**

**Input:** nums = \[3,2,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.

**Example 2:**

**Input:** nums = \[1,2\]
**Output:** 2
**Explanation:**
The first distinct maximum is 2.
The second distinct maximum is 1.
The third distinct maximum does not exist, so the maximum (2) is returned instead.

**Example 3:**

**Input:** nums = \[2,2,3,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2 (both 2's are counted together since they have the same value).
The third distinct maximum is 1.

**Constraints:**

*   `1 <= nums.length <= 104`
*   `-231 <= nums[i] <= 231 - 1`

**Follow up:** Can you find an `O(n)` solution?**SOLUTION:**

    import heapq
    
    class Solution:
        def thirdMax(self, nums: List[int]) -> int:
            dup = set()
            heap = []
            for num in nums:
                if num not in dup:
                    heapq.heappush(heap, num)
                    if len(heap) > 3:
                        heapq.heappop(heap)
                    dup.add(num)
            if len(heap) == 3:
                return heap[0]
            else:
                return max(nums)