title stringlengths 1 100 | titleSlug stringlengths 3 77 | Java int64 0 1 | Python3 int64 1 1 | content stringlengths 28 44.4k | voteCount int64 0 3.67k | question_content stringlengths 65 5k | question_hints stringclasses 970
values |
|---|---|---|---|---|---|---|---|
Simple Python Solution | xor-operation-in-an-array | 0 | 1 | Time Complexcity O(N)\nSpace Complexcity O(1)\n```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n re=start\n for i in range(1,n):\n ne=start+2*i\n re^=ne\n return re\n``` | 1 | You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane.
Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe... | Simulate the process, create an array nums and return the Bitwise XOR of all elements of it. |
Python HashMap beats 100% with detailed comments | making-file-names-unique | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSee comments\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSee comments\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nNote that the while loop will run at most k... | 2 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Python HashMap beats 100% with detailed comments | making-file-names-unique | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSee comments\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSee comments\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nNote that the while loop will run at most k... | 2 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
noob solution | dpm07 | making-file-names-unique | 0 | 1 | \n```\nfrom typing import List\n\n"""\n1487. Making File Names Unique\n\ncreate n folders in your file system such that, at the ith minute, U will create a folder with the name names[i].\n\nSince 2 files cannot have the same name,\nif you enter a folder name that was previously used, the system will have a suffix addit... | 1 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
noob solution | dpm07 | making-file-names-unique | 0 | 1 | \n```\nfrom typing import List\n\n"""\n1487. Making File Names Unique\n\ncreate n folders in your file system such that, at the ith minute, U will create a folder with the name names[i].\n\nSince 2 files cannot have the same name,\nif you enter a folder name that was previously used, the system will have a suffix addit... | 1 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
[Python] ACCEPTED SOLUTION with dictionary (hashmap) and set | making-file-names-unique | 0 | 1 | **Explanation**\nUsing set we check the name which is already user or not, if not used we can keep name\'s version k and increment k until we reach our version.\nIn dictionary, key = name, value = version.\n\n**Complexity**\nTime ```O(N)``` \xA0\nSpace ```O(N)```\n\n```\n from collections import defaultdict\n def... | 22 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
[Python] ACCEPTED SOLUTION with dictionary (hashmap) and set | making-file-names-unique | 0 | 1 | **Explanation**\nUsing set we check the name which is already user or not, if not used we can keep name\'s version k and increment k until we reach our version.\nIn dictionary, key = name, value = version.\n\n**Complexity**\nTime ```O(N)``` \xA0\nSpace ```O(N)```\n\n```\n from collections import defaultdict\n def... | 22 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Python || Dict || No set || Self-Explainable | making-file-names-unique | 0 | 1 | ```\ndef getFolderNames(self, names: List[str]) -> List[str]:\n h = dict()\n ans = []\n \n for i in names:\n if i not in h :\n h[i] = 1\n ans.append(i)\n else:\n ct = h[i]\n tmp = i + \'(\' + str(ct) + \')\'\n ... | 15 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Python || Dict || No set || Self-Explainable | making-file-names-unique | 0 | 1 | ```\ndef getFolderNames(self, names: List[str]) -> List[str]:\n h = dict()\n ans = []\n \n for i in names:\n if i not in h :\n h[i] = 1\n ans.append(i)\n else:\n ct = h[i]\n tmp = i + \'(\' + str(ct) + \')\'\n ... | 15 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Very simple python3 solution using hashmap and comments | making-file-names-unique | 0 | 1 | Very simple and commented solution: \n\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # names : array of names\n # n : size of names\n \n # create folders at the i\'th minute for each name = names[i]\n # If name was used previously, append a suff... | 3 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Very simple python3 solution using hashmap and comments | making-file-names-unique | 0 | 1 | Very simple and commented solution: \n\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # names : array of names\n # n : size of names\n \n # create folders at the i\'th minute for each name = names[i]\n # If name was used previously, append a suff... | 3 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Python3 O(n) using while loop to get the next key name | making-file-names-unique | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing while loop to get the next key name\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nusing while loop to get the next key name\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g.... | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Python3 O(n) using while loop to get the next key name | making-file-names-unique | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing while loop to get the next key name\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nusing while loop to get the next key name\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g.... | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Explication with Python Hash/Dict | making-file-names-unique | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$ average cases\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n #Inicialize hash and new names array\n frequency = {}\n uniqueNames = []\n \n #Foreach name in arra... | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Explication with Python Hash/Dict | making-file-names-unique | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$ average cases\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n #Inicialize hash and new names array\n frequency = {}\n uniqueNames = []\n \n #Foreach name in arra... | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Python - simple | making-file-names-unique | 0 | 1 | # Intuition\nBasically brute force. Store seen names in set, on already seen run dumb counter until you find first number that is not used.\n\n# Complexity\n- Time complexity:\nAverage $$O(NW)$$ - test cases support this \nTeorethical Worst case $$O(N^2W)$$ - for every name (N) processsing within hash table costs in wo... | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Python - simple | making-file-names-unique | 0 | 1 | # Intuition\nBasically brute force. Store seen names in set, on already seen run dumb counter until you find first number that is not used.\n\n# Complexity\n- Time complexity:\nAverage $$O(NW)$$ - test cases support this \nTeorethical Worst case $$O(N^2W)$$ - for every name (N) processsing within hash table costs in wo... | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Clean python use dict beats >95% | making-file-names-unique | 0 | 1 | # Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n folders = dict()\n for i, name in enumerate(names):\n new_name = name\n if name not in folders:\n folders[name] = 0\n else:\n while new_name in folder... | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Clean python use dict beats >95% | making-file-names-unique | 0 | 1 | # Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n folders = dict()\n for i, name in enumerate(names):\n new_name = name\n if name not in folders:\n folders[name] = 0\n else:\n while new_name in folder... | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
easy solution | making-file-names-unique | 0 | 1 | \n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n op = {}\n for i in range(len(names)):\n if names[i] in op:\n b=names[i]+"("+str(op[names[i]])+")"\n op[names[i]]+=1\n while b in op:\n b=names[i... | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix additio... | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
easy solution | making-file-names-unique | 0 | 1 | \n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n op = {}\n for i in range(len(names)):\n if names[i] in op:\n b=names[i]+"("+str(op[names[i]])+")"\n op[names[i]]+=1\n while b in op:\n b=names[i... | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set... | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Python Soln (Greedy | Bisect | BinarySearch) + Comments ! | avoid-flood-in-the-city | 0 | 1 | # Intuition\nGreedy approach: empty the lake when needed\n\n#### Approach\nUse sorted array & binary search to discover which day is available to empty nth lake (S.T. day > n)\n\n#### Complexity\n- Time complexity: $$O(nlogn)$$\n- Space complexity: $$O(n)$$\n\n#### Code\n```\ndef find_gt(a, x):\n \'Find value higher... | 0 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
*... | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
Python Soln (Greedy | Bisect | BinarySearch) + Comments ! | avoid-flood-in-the-city | 0 | 1 | # Intuition\nGreedy approach: empty the lake when needed\n\n#### Approach\nUse sorted array & binary search to discover which day is available to empty nth lake (S.T. day > n)\n\n#### Complexity\n- Time complexity: $$O(nlogn)$$\n- Space complexity: $$O(n)$$\n\n#### Code\n```\ndef find_gt(a, x):\n \'Find value higher... | 0 | A **[binary expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree)** is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes ... | Keep An array of the last day there was rains over each city. Keep an array of the days you can dry a lake when you face one. When it rains over a lake, check the first possible day you can dry this lake and assign this day to this lake. |
HashMap + PQ | avoid-flood-in-the-city | 0 | 1 | # Code\n```\nfrom collections import defaultdict, deque\nfrom heapq import heappop, heappush\nclass Solution:\n def avoidFlood(self, rains: List[int]) -> List[int]:\n d = defaultdict(deque)\n n = len(rains)\n for i in range(n):\n if rains[i]: \n d[rains[i]].append(i)\n ... | 0 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
*... | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
HashMap + PQ | avoid-flood-in-the-city | 0 | 1 | # Code\n```\nfrom collections import defaultdict, deque\nfrom heapq import heappop, heappush\nclass Solution:\n def avoidFlood(self, rains: List[int]) -> List[int]:\n d = defaultdict(deque)\n n = len(rains)\n for i in range(n):\n if rains[i]: \n d[rains[i]].append(i)\n ... | 0 | A **[binary expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree)** is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes ... | Keep An array of the last day there was rains over each city. Keep an array of the days you can dry a lake when you face one. When it rains over a lake, check the first possible day you can dry this lake and assign this day to this lake. |
Python - short with priority qu | avoid-flood-in-the-city | 0 | 1 | # Basic idea\nEverything is described in problem hint.\nHold last index for very value. Process from start index.\nWhen value is met, if exists next index put it on priority queue. When zero pop from pqirioty queue.\nFail is when there is next index equal or smaller to current index or when everything is done and prior... | 0 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
*... | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
Python - short with priority qu | avoid-flood-in-the-city | 0 | 1 | # Basic idea\nEverything is described in problem hint.\nHold last index for very value. Process from start index.\nWhen value is met, if exists next index put it on priority queue. When zero pop from pqirioty queue.\nFail is when there is next index equal or smaller to current index or when everything is done and prior... | 0 | A **[binary expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree)** is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes ... | Keep An array of the last day there was rains over each city. Keep an array of the days you can dry a lake when you face one. When it rains over a lake, check the first possible day you can dry this lake and assign this day to this lake. |
beats 96% memory wise :) | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | \n\n# Code\n```\nclass UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n \n def find_parent(self, p):\n if self.parent[p] != p:\n self.parent[p] = self.find_parent(self.parent[p])\n return self.parent[p]\n \n def union_sets(self, u, v):\n pu, ... | 3 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
100% Best Solution And Easy Understanble With Comments || MST | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
Python3 Solution | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | \n```\nclass Solution :\n def find(self,u,parent):\n if u==parent[u]:\n return u\n return self.find(parent[u],parent)\n\n def unionDSU(self,u,v,parent) :\n p1=self.find(u,parent)\n p2=self.find(v,parent)\n parent[p2]=p1\n\n def mst(self,k,edges,includeEdge,excludeE... | 2 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
Ex-Amazon explains a solution with Python and Java | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 1 | 1 | # Solution Video\nI have to take care of my kids all day. Usually I put a solution video for each question but today, it seems to be hard to create the video.\n\n### Please subscribe to my channel from here. I have 245 videos as of August 19th.\n\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation... | 9 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
Python 3 | Beats Edirotial in Time | Two criteria | O(E^2) | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | # Intuition\nWe need to find an approach to decide whether edge is critical, pseudo-critical or neither of them\n\n# Approach\n1. According to Kruskal\'s algorithm if edge is <ins>_unused_ AND _has minimum weight_ AND _connects two disjoint sets_</ins> **[1]** then there is MST (or MSTs) which includes this edge (reme... | 1 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
Prim's algo (python) | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPrim\'s algo\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g.... | 1 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
Python: Simple and Elegant, Prim's (20lines) | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | # Intuition\n1. Calculate the cost of the Minimum Spanning Tree (MST) as $C$.\n2. For each edge, compute the cost if excluded, denoted as $C_e$, and the cost if included, denoted as $C_i$.\n3. An edge is considered critical if $C_e > C$, and pseudo-critical if $C_e = C = C_i$.\n\n# Complexity\n- Time complexity:\n$$O(E... | 3 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
🔥🔥🔥🔥🔥Beats 100% | JS | TS | Java | C++ | C# | Python | python3 | Kotlin | 🔥🔥🔥🔥🔥 | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 1 | 1 | ---\n\n\n---\n\n```C++ []\nclass UnionFind {\npublic: \n vector<int> parent; \n UnionFind(int n){\n parent.resize(n);\n for(int i=0;i<n;i++)\n parent[i] = i; \n }\n \n... | 68 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
Quick Easy Approach | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | \n\n# Code\n```\nclass UnionFindSet:\n def __init__(self, n=0):\n self.parents = {}\n self.ranks = {}\n self.count = 0\n for i in range(n):\n self.add(i)\n\n def add(self, p):\n self.parents[p] = p\n self.ranks[p] = 1\n self.count += 1\n\n def find(se... | 15 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
✅ 100% - O(ElogE) Kruskal's Algorithm and DFS | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | # Problem Understanding\n\nIn the problem "1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree," we are presented with a weighted undirected connected graph consisting of `n` vertices, numbered from 0 to `n - 1`. The graph is described by an array `edges`, where each element `edges[i] = [ai, bi, weig... | 23 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
🔥Easy Solution 🔥Python3/C/C#/C++/Java🔥Use MST algorihtm🔥With 🗺️Image🗺️ | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 1 | 1 | # Intuition\nTo your preferred programming language\nyou can turn.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```... | 9 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices withou... | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic... |
Dynamic average calculation (to avoid overflow) | average-salary-excluding-the-minimum-and-maximum-salary | 0 | 1 | This approach works for the case when all the values are positive and array may contain values till $$10^9$$. In this case a simple summation will overflow.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n##### **Dynamic average calculation**\nCase 1: Element Incoming\n```\nnew_avg = avg + (elem... | 1 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Dynamic average calculation (to avoid overflow) | average-salary-excluding-the-minimum-and-maximum-salary | 0 | 1 | This approach works for the case when all the values are positive and array may contain values till $$10^9$$. In this case a simple summation will overflow.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n##### **Dynamic average calculation**\nCase 1: Element Incoming\n```\nnew_avg = avg + (elem... | 1 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Simple Python3 & Java Solution|| Upto 100% faster || O(n) | average-salary-excluding-the-minimum-and-maximum-salary | 1 | 1 | # Intuition\nWe first initializes two variables, max_sal and min_sal, to 0 and 100000 respectively. \nIt then loops over each element i in the input array salary and updates max_sal and min_sal if i is greater than max_sal or less than min_sal, respectively.\n\nThen sum minus max & min values and averge of the sum of s... | 1 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Simple Python3 & Java Solution|| Upto 100% faster || O(n) | average-salary-excluding-the-minimum-and-maximum-salary | 1 | 1 | # Intuition\nWe first initializes two variables, max_sal and min_sal, to 0 and 100000 respectively. \nIt then loops over each element i in the input array salary and updates max_sal and min_sal if i is greater than max_sal or less than min_sal, respectively.\n\nThen sum minus max & min values and averge of the sum of s... | 1 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Non_optimised.py | average-salary-excluding-the-minimum-and-maximum-salary | 0 | 1 | # Code\n```\nclass Solution:\n def average(self, salary: List[int]) -> float:\n salary.sort()\n ans=sum(salary)\n ans-=salary[0]\n ans-=salary[len(salary)-1]\n return ans/(len(salary)-2)\n``` | 1 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Ou... | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Non_optimised.py | average-salary-excluding-the-minimum-and-maximum-salary | 0 | 1 | # Code\n```\nclass Solution:\n def average(self, salary: List[int]) -> float:\n salary.sort()\n ans=sum(salary)\n ans-=salary[0]\n ans-=salary[len(salary)-1]\n return ans/(len(salary)-2)\n``` | 1 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Easy solution in python | the-kth-factor-of-n | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12,... | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
Easy solution in python | the-kth-factor-of-n | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
Beats 100% memory☺ | the-kth-factor-of-n | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12,... | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
Beats 100% memory☺ | the-kth-factor-of-n | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
[Python] naive -> factor pairs -> jump to next pair 🤯 | the-kth-factor-of-n | 0 | 1 | # (1) checking every factor\n\nSimply check for every number from $$2$$ to $$n$$ if it is divisible by $$n$$ and push it to the stack.\n\n### Code\n```Python\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n factors=[1]\n for i in range(2,n+1):\n if n%i==0:\n fa... | 1 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12,... | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
[Python] naive -> factor pairs -> jump to next pair 🤯 | the-kth-factor-of-n | 0 | 1 | # (1) checking every factor\n\nSimply check for every number from $$2$$ to $$n$$ if it is divisible by $$n$$ and push it to the stack.\n\n### Code\n```Python\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n factors=[1]\n for i in range(2,n+1):\n if n%i==0:\n fa... | 1 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
Python | O(sqrt(n)) with Explaination | top 95% | the-kth-factor-of-n | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe obtain O(sqrt(n)) time utilizing the fact that n divided by a factor obtains two factors. For example, 12 / 3 = 4, so we know both 3 and 4 are factors. Thus, we only need to check factors up until sqrt(n) because all other factors larger than sqr... | 4 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12,... | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
Python | O(sqrt(n)) with Explaination | top 95% | the-kth-factor-of-n | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe obtain O(sqrt(n)) time utilizing the fact that n divided by a factor obtains two factors. For example, 12 / 3 = 4, so we know both 3 and 4 are factors. Thus, we only need to check factors up until sqrt(n) because all other factors larger than sqr... | 4 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
✅Beat's 100% || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | longest-subarray-of-1s-after-deleting-one-element | 1 | 1 | # Intuition:\nThe Intuition is to use a sliding window approach to find the length of the longest subarray of 1\'s after removing at most one element (0 or 1) from the original array. It adjusts the window to have at most one zero, calculates the subarray length, and returns the maximum length found.\n\n# Explanation:\... | 217 | 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 pos... | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. |
Binary Search + Sliding Window Solution | longest-subarray-of-1s-after-deleting-one-element | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs we have to maximize the answer and we know the minimum and maximum possible answer and this is a sub array problem, so why not think of a binary search and sliding window solution?\n\n# Approach\n<!-- Describe your approach to solving ... | 1 | 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 pos... | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. |
Python short and clean. Functional programming. | longest-subarray-of-1s-after-deleting-one-element | 0 | 1 | # Approach\n1. For every element `x` in `nums`, calculate the length of streaks of `1s` upto `x` excluding itself.\n\n2. Select the streaks corresponding to `x == 0`, lets call it `streaks_at_0`. This acts as deleting the corresponding `x` and selecting the streaks of `1s` to the left of it.\n\n3. The longest possible ... | 1 | 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 pos... | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. |
Detailed Explanations + Diagrams + Annotated Code | parallel-courses-ii | 0 | 1 | ## 0. Preface\nThis is a *really* good problem. However, the solutions I found were either too complex or just did not make any sense. In this post, I\'ll attempt to explain everything from top to bottom.\n\n## 1. Understading the Problem\n**Given**:\n- There are courses from `1 to n`, both inclusive.\n- There are rela... | 115 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be take... | null |
Python -- Hopefully a more readable solution, ~80% | parallel-courses-ii | 0 | 1 | \n<!-- Describe your first thoughts on how to solve this problem. -->\nHad to read and understand the approach by others to come up with this. Looks like FAANG is a pipe dream for me :(\n\nHopefully this share helps someone else in their journey :)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\... | 0 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be take... | null |
Python3 clean and concise solution beating ~93% with dp and bitmask | parallel-courses-ii | 0 | 1 | DFS and BFS would fail without pruning or memoization as there are a lot of branches that share the same states. \n\nAs hinted, use \'seen\' which is a bitmask for coursed that are taken as the key in the dp that could be memoized. The other state marker would be the semesters it has taken so far. Seen would be of the ... | 0 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be take... | null |
SOLID Principles | Commented and Explained | Bellman Ford | parallel-courses-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo get the minimal semesters needed, we need a topological sorting approach. However, this question can never be well suited, as I\'ll point out below, so we are forced to try an exhaustive search methodology. However, some improvements c... | 0 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be take... | null |
Beginner Friendly || Beats 95% || Fully Explained || [Java/C++/Python3] | path-crossing | 1 | 1 | # Approach\n1. **Initialization:** Initialize a HashSet (set) to store visited coordinates. Initialize x and y to represent the current position, and add the starting coordinate ("0,0") to the set.\n2. **Traversal:** Iterate through each character in the input path string. Update the coordinates based on the direction ... | 1 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Beginner Friendly || Beats 95% || Fully Explained || [Java/C++/Python3] | path-crossing | 1 | 1 | # Approach\n1. **Initialization:** Initialize a HashSet (set) to store visited coordinates. Initialize x and y to represent the current position, and add the starting coordinate ("0,0") to the set.\n2. **Traversal:** Iterate through each character in the input path string. Update the coordinates based on the direction ... | 1 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Path Crossing (Storing the traversed positonss...) | path-crossing | 0 | 1 | # Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nDepending upon the movements the positions is changed and the new position is added to a list and check whether the postion is already visited...\n\n Trace the position visited by using a pair of values [x,y] \nstart the poi... | 3 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Path Crossing (Storing the traversed positonss...) | path-crossing | 0 | 1 | # Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nDepending upon the movements the positions is changed and the new position is added to a list and check whether the postion is already visited...\n\n Trace the position visited by using a pair of values [x,y] \nstart the poi... | 3 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
You don't need matrices and graphs to solve this!!! | path-crossing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
You don't need matrices and graphs to solve this!!! | path-crossing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python || Easy Clean Set Solution. | path-crossing | 0 | 1 | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n seen = set([\'0_0\'])\n curr = [0, 0]\n ... | 1 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python || Easy Clean Set Solution. | path-crossing | 0 | 1 | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n seen = set([\'0_0\'])\n curr = [0, 0]\n ... | 1 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Simple Python || Understandable & Clean | path-crossing | 0 | 1 | # My Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n (r, c) = (0, 0)\n coors = {(r, c)}\n for i in path:\n if i == \'N\': c += 1\n elif i == \'E\': r += 1\n elif i == \'S\': c -= 1\n else: r -= 1\n if (r, c) in co... | 2 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Simple Python || Understandable & Clean | path-crossing | 0 | 1 | # My Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n (r, c) = (0, 0)\n coors = {(r, c)}\n for i in path:\n if i == \'N\': c += 1\n elif i == \'E\': r += 1\n elif i == \'S\': c -= 1\n else: r -= 1\n if (r, c) in co... | 2 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python3 simple solution faster than 99% users | path-crossing | 0 | 1 | ```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n l = [(0,0)]\n x,y = 0,0\n for i in path:\n if i == \'N\':\n y += 1\n if i == \'S\':\n y -= 1\n if i == \'E\':\n x += 1\n if i == \'W\':\n... | 4 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python3 simple solution faster than 99% users | path-crossing | 0 | 1 | ```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n l = [(0,0)]\n x,y = 0,0\n for i in path:\n if i == \'N\':\n y += 1\n if i == \'S\':\n y -= 1\n if i == \'E\':\n x += 1\n if i == \'W\':\n... | 4 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
python dict beats 89% | path-crossing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
python dict beats 89% | path-crossing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Simple Hashing solution Beats 97% | path-crossing | 0 | 1 | # Intuition\nThe problem requires tracking a path determined by a series of directions and checking if the path crosses itself. Intuitively, this involves keeping track of all the points visited during the traversal of the path. If any point is visited more than once, the path crosses itself.\n\n# Approach\nTo implemen... | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Simple Hashing solution Beats 97% | path-crossing | 0 | 1 | # Intuition\nThe problem requires tracking a path determined by a series of directions and checking if the path crosses itself. Intuitively, this involves keeping track of all the points visited during the traversal of the path. If any point is visited more than once, the path crosses itself.\n\n# Approach\nTo implemen... | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python Solution with short circuit. | path-crossing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere we construct the locations of the path and short circut if at any time we arrive at a location we\'ve been previously. We achieve this with the use of a Counter whose keys are the immutable tuple locations.\n\n# Code\n```\nclass Solu... | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python Solution with short circuit. | path-crossing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere we construct the locations of the path and short circut if at any time we arrive at a location we\'ve been previously. We achieve this with the use of a Counter whose keys are the immutable tuple locations.\n\n# Code\n```\nclass Solu... | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python solution using set and dictionary | path-crossing | 0 | 1 | # Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n x,y=0,0\n coords = set()\n coords.add((x,y))\n dic = {\'N\':(0,1),\'E\':(1,0),\'S\':(0,-1),\'W\':(-1,0)}\n for p in path:\n x+= dic[p][0]\n y+= dic[p][1]\n if((x,y) in coo... | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python solution using set and dictionary | path-crossing | 0 | 1 | # Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n x,y=0,0\n coords = set()\n coords.add((x,y))\n dic = {\'N\':(0,1),\'E\':(1,0),\'S\':(0,-1),\'W\':(-1,0)}\n for p in path:\n x+= dic[p][0]\n y+= dic[p][1]\n if((x,y) in coo... | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python3 - Fast (~97%) but memory heavy (~23%) | path-crossing | 0 | 1 | \n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n def get_next_point(point, prev):\n return [prev[0] + point[0], prev[1] + point[1]]\n\n start = [0, 0]\n coords = [start]\n\n N = [1, 0]\n S = [-1, 0]\n E = [0, 1]\n W = [0, -1]\n\n ... | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you ... | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python3 - Fast (~97%) but memory heavy (~23%) | path-crossing | 0 | 1 | \n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n def get_next_point(point, prev):\n return [prev[0] + point[0], prev[1] + point[1]]\n\n start = [0, 0]\n coords = [start]\n\n N = [1, 0]\n S = [-1, 0]\n E = [0, 1]\n W = [0, -1]\n\n ... | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
... | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python One liner Explained with 2 Original Solutions( The best explanation) | check-if-array-pairs-are-divisible-by-k | 0 | 1 | The idea is to check the total sum divisible by k.if there has to be n//2 pairs each sum divisible by k.And this worksout well because,even if there is a singlepair whose sum not divisible by k,the total sum concept fails.\n\nMaybe,its just `intuition` sometimes.I Solved it in the contest in 1sec with `one liner`.Read ... | 54 | You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**.
You are al... | Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0 |
Python One liner Explained with 2 Original Solutions( The best explanation) | check-if-array-pairs-are-divisible-by-k | 0 | 1 | The idea is to check the total sum divisible by k.if there has to be n//2 pairs each sum divisible by k.And this worksout well because,even if there is a singlepair whose sum not divisible by k,the total sum concept fails.\n\nMaybe,its just `intuition` sometimes.I Solved it in the contest in 1sec with `one liner`.Read ... | 54 | Design a stack which supports the following operations. Implement the CustomStack class: | Use an array to represent the stack. Push will add new integer to the array. Pop removes the last element in the array and increment will add val to the first k elements of the array. This solution run in O(1) per push and pop and O(k) per increment. |
Most of the Solutions here are wrong. Correct solution is here. | check-if-array-pairs-are-divisible-by-k | 0 | 1 | I have seen other solutions but I dont think most of them will work. Test cases are weak actually.\nEx: arr = [2,2,2,2,2,2] k = 3\n\nThis is my implementation for this problem.\n```\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n ## RC ##\n ## APPROACH : 2 SUM ##\n ##... | 43 | You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**.
You are al... | Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0 |
Most of the Solutions here are wrong. Correct solution is here. | check-if-array-pairs-are-divisible-by-k | 0 | 1 | I have seen other solutions but I dont think most of them will work. Test cases are weak actually.\nEx: arr = [2,2,2,2,2,2] k = 3\n\nThis is my implementation for this problem.\n```\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n ## RC ##\n ## APPROACH : 2 SUM ##\n ##... | 43 | Design a stack which supports the following operations. Implement the CustomStack class: | Use an array to represent the stack. Push will add new integer to the array. Pop removes the last element in the array and increment will add val to the first k elements of the array. This solution run in O(1) per push and pop and O(k) per increment. |
[Python 3] Two Sum Variation | Hashmap | O(n) | check-if-array-pairs-are-divisible-by-k | 0 | 1 | ```\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n hm = defaultdict(int)\n res = 0\n \n for i in arr:\n temp = i % k\n \n if temp == 0:\n res += 1\n elif k - temp in hm and hm[k - temp] != 0:\n ... | 1 | You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**.
You are al... | Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0 |
[Python 3] Two Sum Variation | Hashmap | O(n) | check-if-array-pairs-are-divisible-by-k | 0 | 1 | ```\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n hm = defaultdict(int)\n res = 0\n \n for i in arr:\n temp = i % k\n \n if temp == 0:\n res += 1\n elif k - temp in hm and hm[k - temp] != 0:\n ... | 1 | Design a stack which supports the following operations. Implement the CustomStack class: | Use an array to represent the stack. Push will add new integer to the array. Pop removes the last element in the array and increment will add val to the first k elements of the array. This solution run in O(1) per push and pop and O(k) per increment. |
python3 code | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
python3 code | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do n... | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
2_Pointor.py | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Approach\nTwo Pointer\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n\n# Code\n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n ans=0\n i,j=0,len(nums)-1\n while i<=j:\n if nums[i]+nums[j]>target:\n j-=1\n ... | 2 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
2_Pointor.py | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Approach\nTwo Pointer\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n\n# Code\n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n ans=0\n i,j=0,len(nums)-1\n while i<=j:\n if nums[i]+nums[j]>target:\n j-=1\n ... | 2 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do n... | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
python3 Solution | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | \n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n ans=0\n mod=10**9+7\n for index,x in enumerate(nums):\n n=bisect.bisect_right(nums,target-x)-1\n if n-index-1>=0:\n ans+=pow(2,n-index,mod)-1\n\n ... | 2 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
python3 Solution | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | \n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n ans=0\n mod=10**9+7\n for index,x in enumerate(nums):\n n=bisect.bisect_right(nums,target-x)-1\n if n-index-1>=0:\n ans+=pow(2,n-index,mod)-1\n\n ... | 2 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do n... | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
classify all the answer by [min, max] pairs | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
classify all the answer by [min, max] pairs | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do n... | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
1498. Number of Subsequences That Satisfy the Given Sum Condition.py | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
1498. Number of Subsequences That Satisfy the Given Sum Condition.py | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do n... | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
Python 3 Solution || Two Pointer || Easy to understand | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n) \n<!-- Add your space complexity h... | 1 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums =... | null |
Python 3 Solution || Two Pointer || Easy to understand | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n) \n<!-- Add your space complexity h... | 1 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do n... | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
[Python3] heap | max-value-of-equation | 0 | 1 | Algo\nSince the target to be optimized is `yi + yj + |xi - xj|` (aka `xj + yj + yi - xi` given `j > i`), the value of interest is `yi - xi`. While we loop through the array with index `j`, we want to keep track of the largest `yi - xi` under the constraint that `xj - xi <= k`. \n\nWe could use a priority queue for this... | 9 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` ... | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.