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 |
|---|---|---|---|---|---|---|---|
[Java/Python 3] Sort by trimmed string. | query-kth-smallest-trimmed-number | 1 | 1 | \n```java\n public int[] smallestTrimmedNumbers(String[] nums, int[][] queries) {\n int n = queries.length, j = 0;\n int[] ans = new int[n];\n Map<Integer, String[][]> trimmed = new HashMap<>();\n for (int[] q : queries) {\n int k = q[0] - 1;\n int trim = q[1];\n ... | 14 | You are given a **0-indexed** array of strings `nums`, where each string is of **equal length** and consists of only digits.
You are also given a **0-indexed** 2D integer array `queries` where `queries[i] = [ki, trimi]`. For each `queries[i]`, you need to:
* **Trim** each number in `nums` to its **rightmost** `trim... | null |
Heap of size K for Kth smallest number|Python3|Similar to Kth smallest Element|Easy to understand | query-kth-smallest-trimmed-number | 0 | 1 | \nPlease upvote if you liked this\n\n**Note** :We have stored -ve index , because if we have case like in heap , we have [[4,2],[4,3]] . We want to return 3 , but if we perfrom heapq.heappop(). We will get result 2.\n```\n\nclass Solution:\n def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]... | 3 | You are given a **0-indexed** array of strings `nums`, where each string is of **equal length** and consists of only digits.
You are also given a **0-indexed** 2D integer array `queries` where `queries[i] = [ki, trimi]`. For each `queries[i]`, you need to:
* **Trim** each number in `nums` to its **rightmost** `trim... | null |
Python Commented Code ( Insertion + Customization for storing index) | query-kth-smallest-trimmed-number | 0 | 1 | ```\nclass Solution:\n def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]:\n a=[] #to store answer of queries\n for q in queries: \n ia=q[0] #kth smallest value to be returned\n t=q[1] #trim ... | 2 | You are given a **0-indexed** array of strings `nums`, where each string is of **equal length** and consists of only digits.
You are also given a **0-indexed** 2D integer array `queries` where `queries[i] = [ki, trimi]`. For each `queries[i]`, you need to:
* **Trim** each number in `nums` to its **rightmost** `trim... | null |
Python O(m * n) solution based on O(m) counting sort | query-kth-smallest-trimmed-number | 0 | 1 | Algorithm itself is simple to understand, using counting-based sort instead of comparison-based sort to get rid of the O(lgm) part in time complexity. \n\nReferenced the super concise implementation from this post: https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2292577/Python-O(mnlogm).-Sort-am... | 4 | You are given a **0-indexed** array of strings `nums`, where each string is of **equal length** and consists of only digits.
You are also given a **0-indexed** 2D integer array `queries` where `queries[i] = [ki, trimi]`. For each `queries[i]`, you need to:
* **Trim** each number in `nums` to its **rightmost** `trim... | null |
asy-4-line-soln👁️ | well-explained✅ | Microsoft🔥 | minimum-deletions-to-make-array-divisible | 0 | 1 | # Please upvote if it is helpful ^_^\n*6Companies30days #ReviseWithArsh Challenge 2023\nDay3\nQ14. Deletions to make an array divisible.*\n\n**Intuition: *gcd***\n\n\... | 1 | You are given two positive integer arrays `nums` and `numsDivide`. You can delete any number of elements from `nums`.
Return _the **minimum** number of deletions such that the **smallest** element in_ `nums` _**divides** all the elements of_ `numsDivide`. If this is not possible, return `-1`.
Note that an integer `x`... | null |
[Java/Python 3] 2 methods about GCD w/ brief explanation and analysis. | minimum-deletions-to-make-array-divisible | 1 | 1 | "divide all numbers in `numsDivide`" implies "divide the gcd of `numsDivide`". Therefore, we can design an algorithm as follows:\n\n----\n\n**Method 1:**\n1. Compute the gcd of `numsDivide`;\n2. Traverse `nums` to find the smallest number that can divide the gcd;; If fails, return -1\n3. Traverse `nums` to count how m... | 10 | You are given two positive integer arrays `nums` and `numsDivide`. You can delete any number of elements from `nums`.
Return _the **minimum** number of deletions such that the **smallest** element in_ `nums` _**divides** all the elements of_ `numsDivide`. If this is not possible, return `-1`.
Note that an integer `x`... | null |
Python3 || GCD and heap, 6 lines, w/ explanation || T/M: 56%/100% | minimum-deletions-to-make-array-divisible | 0 | 1 | ```\nclass Solution:\n # From number theory, we know that an integer num divides each\n # integer in a list if and only if num divides the list\'s gcd.\n # \n # Our plan here is to:\n # \u2022 find the gcd of numDivide\n ... | 3 | You are given two positive integer arrays `nums` and `numsDivide`. You can delete any number of elements from `nums`.
Return _the **minimum** number of deletions such that the **smallest** element in_ `nums` _**divides** all the elements of_ `numsDivide`. If this is not possible, return `-1`.
Note that an integer `x`... | null |
GCD and heaps | Python3 | Explained | minimum-deletions-to-make-array-divisible | 0 | 1 | 1. Calculate the GCD of numsDivide array\n2. heapify the nums array \n3. Pop elements from the nums array until it is not dividing the GCD in step 1\n\n```\nclass Solution:\n def minOperations(self, nums: List[int], numsDivide: List[int]) -> int:\n \n def GcdOfArray(arr, idx):\n if idx == le... | 0 | You are given two positive integer arrays `nums` and `numsDivide`. You can delete any number of elements from `nums`.
Return _the **minimum** number of deletions such that the **smallest** element in_ `nums` _**divides** all the elements of_ `numsDivide`. If this is not possible, return `-1`.
Note that an integer `x`... | null |
[Java/Python 3] 3 conditionals w/ brief explanation and analysis. | best-poker-hand | 1 | 1 | 1. If all characters in `suits` are same, then it is `Flush`;\n2. If there are at least `3` values in `ranks` are same, it is `Three of a Kind`;\n3. If there are`2` values in `ranks` are same, it is `Pair`;\n4. Otherwise, it is `High Card`.\n\n```java\n public String bestHand(int[] r, char[] s) {\n int[] cnt ... | 10 | You are given an integer array `ranks` and a character array `suits`. You have `5` cards where the `ith` card has a rank of `ranks[i]` and a suit of `suits[i]`.
The following are the types of **poker hands** you can make from best to worst:
1. `"Flush "`: Five cards of the same suit.
2. `"Three of a Kind "`: Three ... | null |
Python | Easy & Understanding Solution | best-poker-hand | 0 | 1 | ```\nclass Solution:\n def bestHand(self, ranks: List[int], suits: List[str]) -> str:\n if(len(set(suits))==1):\n return "Flush"\n \n mp={}\n \n for i in range(5):\n if(ranks[i] not in mp):\n mp[ranks[i]]=1\n else:\n mp... | 1 | You are given an integer array `ranks` and a character array `suits`. You have `5` cards where the `ith` card has a rank of `ranks[i]` and a suit of `suits[i]`.
The following are the types of **poker hands** you can make from best to worst:
1. `"Flush "`: Five cards of the same suit.
2. `"Three of a Kind "`: Three ... | null |
Python || easy colution | best-poker-hand | 0 | 1 | ```\nclass Solution:\n def bestHand(self, ranks: List[int], suits: List[str]) -> str:\n N = len(ranks)\n statistic = defaultdict(int)\n\n letter_freq = 0\n number_freq = 0\n\n for i in range(N):\n statistic[ranks[i]] += 1\n statistic[suits[i]] += 1\n ... | 1 | You are given an integer array `ranks` and a character array `suits`. You have `5` cards where the `ith` card has a rank of `ranks[i]` and a suit of `suits[i]`.
The following are the types of **poker hands** you can make from best to worst:
1. `"Flush "`: Five cards of the same suit.
2. `"Three of a Kind "`: Three ... | null |
Python 1-liner. Functional programming. | number-of-zero-filled-subarrays | 0 | 1 | # Approach\nTL;DR, same as [Official solution](https://leetcode.com/problems/number-of-zero-filled-subarrays/editorial/) but written in a declarative and functional way.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\nwhere, `n is the length of nums`.\n\n# Code\n```python\nclass Solution... | 6 | Given an integer array `nums`, return _the number of **subarrays** filled with_ `0`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,3,0,0,2,0,0,4\]
**Output:** 6
**Explanation:**
There are 4 occurrences of \[0\] as a subarray.
There are 2 occurren... | null |
Python Readable - Simple Intuition | number-of-zero-filled-subarrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. What exactly are zero filled subarrays?\n2. What are you trying to find with zero filled subarrays? -> [0], [0,0], [0,0,0] ...\n3. Once you have found array [0,0,0] or [0,0], how many subarrays exist in this subarray? -> Math Trick sum... | 2 | Given an integer array `nums`, return _the number of **subarrays** filled with_ `0`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,3,0,0,2,0,0,4\]
**Output:** 6
**Explanation:**
There are 4 occurrences of \[0\] as a subarray.
There are 2 occurren... | null |
Unveil Logic with Crazy Solution | number-of-zero-filled-subarrays | 0 | 1 | \n\n# Superb Logic---->O(N) \n```\nclass Solution:\n def zeroFilledSubarray(self, nums: List[int]) -> int:\n answer=count=0\n for i in nums:\n if i==0: count+=1\n else:count=0\n answer+=count\n return answer\n\n```\n# please upvote me it would encourage me alot\n | 2 | Given an integer array `nums`, return _the number of **subarrays** filled with_ `0`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,3,0,0,2,0,0,4\]
**Output:** 6
**Explanation:**
There are 4 occurrences of \[0\] as a subarray.
There are 2 occurren... | null |
O(n) time complexity and O(n) space complexity | number-of-zero-filled-subarrays | 0 | 1 | \n\n\n# Intuition\nThe code aims to find the number of subarrays filled with 0 in the given integer array nums. It does this by iterating through the array and identifying the subarrays filled with 0. The i... | 1 | Given an integer array `nums`, return _the number of **subarrays** filled with_ `0`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,3,0,0,2,0,0,4\]
**Output:** 6
**Explanation:**
There are 4 occurrences of \[0\] as a subarray.
There are 2 occurren... | null |
python3 || dp||easy to understand|| get the pattern|| dictionary|| | number-of-zero-filled-subarrays | 0 | 1 | \'\'\':\n\n\n\t\t\t\t\tthe pattern is here: {1:1,2:3,3:6,4:10,5:15,6:21} ={number of zeros:answer}\n\t\t\t\t\tif the question is [0,0] the answer becomes 3.\n\t\t\t\t\tbut if the question becomes like this [0,0,1,0,0] the answer becomes 6 which means 3+3\n\t\t\t\t\t[0,0] = 3 , [0,0] = 3 , [0,0,1,0,0] = 3+3 = 6\n\t\t\n\... | 1 | Given an integer array `nums`, return _the number of **subarrays** filled with_ `0`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,3,0,0,2,0,0,4\]
**Output:** 6
**Explanation:**
There are 4 occurrences of \[0\] as a subarray.
There are 2 occurren... | null |
easiest two approaches loop using in python3 | number-of-zero-filled-subarrays | 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 `nums`, return _the number of **subarrays** filled with_ `0`.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,3,0,0,2,0,0,4\]
**Output:** 6
**Explanation:**
There are 4 occurrences of \[0\] as a subarray.
There are 2 occurren... | null |
DEAR MJ | design-a-number-container-system | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing two hashmap(dictionary, set) and renew the min index of the value each time we call the method \'change\'\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ndescription is in the code\n\n# Complexity\n- Time com... | 1 | Design a number container system that can do the following:
* **Insert** or **Replace** a number at the given index in the system.
* **Return** the smallest index for the given number in the system.
Implement the `NumberContainers` class:
* `NumberContainers()` Initializes the number container system.
* `voi... | null |
[Java/Python 3] TreeSet/SortedList w/ brief explanation and analysis. | design-a-number-container-system | 1 | 1 | **Q & A**\n\nQ1: How many third party packages are pre installed on leetcode server? And where to get such list?\nA1: Please see [What are the environments for the programming languages?](https://support.leetcode.com/hc/en-us/articles/360011833974-What-are-the-environments-for-the-programming-languages-).\n\nQ2: Why `f... | 44 | Design a number container system that can do the following:
* **Insert** or **Replace** a number at the given index in the system.
* **Return** the smallest index for the given number in the system.
Implement the `NumberContainers` class:
* `NumberContainers()` Initializes the number container system.
* `voi... | null |
Heap + Hashmap Python3 Solution | design-a-number-container-system | 0 | 1 | ```\nclass NumberContainers:\n\n def __init__(self):\n self.num_indices = defaultdict(list)\n self.num_at_index = {}\n \n\n def change(self, index: int, number: int) -> None:\n self.num_at_index[index] = number\n heapq.heappush(self.num_indices[number], index)\n \n\n d... | 1 | Design a number container system that can do the following:
* **Insert** or **Replace** a number at the given index in the system.
* **Return** the smallest index for the given number in the system.
Implement the `NumberContainers` class:
* `NumberContainers()` Initializes the number container system.
* `voi... | null |
Python easy understanding solution | shortest-impossible-sequence-of-rolls | 0 | 1 | For example, k = 3, rolls = [1, 1, 2, 2, 3, 1]\nUse a set to record if all possible numbers has appeared at least once.\nIn this case, when iterate to 3 in [1, 1, 2, 2, **3**, 1], all possible numbers (1-3) has appeared at least once,\nso you must at least take 1 number from interval [1, 1, 2, 2, 3], in practice, tak... | 1 | You are given an integer array `rolls` of length `n` and an integer `k`. You roll a `k` sided dice numbered from `1` to `k`, `n` times, where the result of the `ith` roll is `rolls[i]`.
Return _the length of the **shortest** sequence of rolls that **cannot** be taken from_ `rolls`.
A **sequence of rolls** of length `... | null |
Beats 77.4% | first-letter-to-appear-twice | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n l=\'\'\n for i in range(len(s)):\n if s[i] in l:\n return s[i]\n else:\n l=l+s[i]\n return l \n``` | 1 | Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_.
**Note**:
* A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`.
* `s` will contain at least one letter that appears twice.
**... | null |
🔥100% EASY TO UNDERSTAND/SIMPLE/CLEAN🔥 | first-letter-to-appear-twice | 0 | 1 | ```\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n seenAlready = []\n for c in s:\n if c not in seenAlready:\n seenAlready.append(c)\n else:\n return c | 0 | Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_.
**Note**:
* A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`.
* `s` will contain at least one letter that appears twice.
**... | null |
✅Python || Map || Easy Approach | first-letter-to-appear-twice | 0 | 1 | Algorithm:\n(1) use setS to store the letter have ever seen;\n(2) one pass the input string:\n(3) if x is already in setS:\n\t\tx is what we need (it is the first occurrence twice).\n(4) else (x is not in setS):\n\t\twe put the x into the setS to store it.\n```\nclass Solution:\n def repeatedCharacter(self, s: str) ... | 19 | Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_.
**Note**:
* A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`.
* `s` will contain at least one letter that appears twice.
**... | null |
Python Simple Code (Hash Table , Set, List) | first-letter-to-appear-twice | 0 | 1 | **If you got help from this,... Plz Upvote .. it encourage me**\n\n# Code\n> # HashTable\n```\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n d = {}\n for char in s:\n if char in d:\n return char\n else:\n d[char] = 1\n\n ... | 3 | Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_.
**Note**:
* A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`.
* `s` will contain at least one letter that appears twice.
**... | null |
Python Elegant & Short | O(n) time & O(1) space | Set | first-letter-to-appear-twice | 0 | 1 | \tdef repeatedCharacter(self, s: str) -> str:\n\t\tseen = set()\n\n\t\tfor c in s:\n\t\t\tif c in seen:\n\t\t\t\treturn c\n\t\t\tseen.add(c)\n | 3 | Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_.
**Note**:
* A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`.
* `s` will contain at least one letter that appears twice.
**... | null |
Python | Easy Solution✅ | first-letter-to-appear-twice | 0 | 1 | ```\ndef repeatedCharacter(self, s: str) -> str:\n st = set()\n for i in range(len(s)): # s = "abccbaacz"\n if s[i] in st: # condition will be true when i = 3\n return s[i] # return c\n else:\n st.add(s[i]) # st = {a,b,c}\n``` | 4 | Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_.
**Note**:
* A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`.
* `s` will contain at least one letter that appears twice.
**... | null |
Easiest python solution to understand for beginners | equal-row-and-column-pairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem aims to count the number of equal pairs in the given grid. One way to approach this is to compare each row in the grid with the first row and check if they are equal.\n# Approach\n<!-- Describe your approach to solving the pro... | 4 | Given a **0-indexed** `n x n` integer matrix `grid`, _return the number of pairs_ `(ri, cj)` _such that row_ `ri` _and column_ `cj` _are equal_.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
**Example 1:**
**Input:** grid = \[\[3,2,1\],\[1,7,6\]... | null |
Understandable solution with python3 | equal-row-and-column-pairs | 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 **0-indexed** `n x n` integer matrix `grid`, _return the number of pairs_ `(ri, cj)` _such that row_ `ri` _and column_ `cj` _are equal_.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
**Example 1:**
**Input:** grid = \[\[3,2,1\],\[1,7,6\]... | null |
Python3 Solution | equal-row-and-column-pairs | 0 | 1 | \n```\nclass Solution:\n def equalPairs(self, grid: List[List[int]]) -> int:\n counter=collections.Counter()\n for row in grid:\n counter[tuple(row)]+=1\n\n\n ans=0\n n=len(grid)\n for i in range(n):\n now=[]\n for j in range(n):\n no... | 1 | Given a **0-indexed** `n x n` integer matrix `grid`, _return the number of pairs_ `(ri, cj)` _such that row_ `ri` _and column_ `cj` _are equal_.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
**Example 1:**
**Input:** grid = \[\[3,2,1\],\[1,7,6\]... | null |
Easy & Clear Solution | equal-row-and-column-pairs | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def equalPairs(self, grid: List[List[int]]) -> int:\n sumrow=[]\n sumcol=[]\n n=len(grid)\n for i in range(n):\n sumrow.append(sum(grid[i]))\n s=0\n for j in range(n):\n s+=grid[j][i]\n sumcol.ap... | 5 | Given a **0-indexed** `n x n` integer matrix `grid`, _return the number of pairs_ `(ri, cj)` _such that row_ `ri` _and column_ `cj` _are equal_.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
**Example 1:**
**Input:** grid = \[\[3,2,1\],\[1,7,6\]... | null |
Java✔ || C++✔ ||Python✔ || Easy To Understand | equal-row-and-column-pairs | 1 | 1 | # Guys Please Vote up )):\nTo solve this problem, we can iterate through each row and column of the grid and check if they contain the same elements in the same order. If they do, we increment a counter. Finally, we return the value of the counter.\n\n# Approach\nHere\'s the approach to solve the problem:\n\n Initia... | 57 | Given a **0-indexed** `n x n` integer matrix `grid`, _return the number of pairs_ `(ri, cj)` _such that row_ `ri` _and column_ `cj` _are equal_.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
**Example 1:**
**Input:** grid = \[\[3,2,1\],\[1,7,6\]... | null |
✅☑[C++/C/Java/Python/JavaScript] || 2 Approaches || Beats 100% || EXPLAINED🔥 | design-a-food-rating-system | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n*(Also explained in the code)*\n\n#### ***Approaches 1(Maps with Queue)***\n1. **Food Class:** Represents a food item with its rating and name.\n\n1. **FoodRatings Class:** Manages food ratings and cuisines using maps and priority queues.\n\n - **foodRatingMap:*... | 59 | Design a food rating system that can do the following:
* **Modify** the rating of a food item listed in the system.
* Return the highest-rated food item for a type of cuisine in the system.
Implement the `FoodRatings` class:
* `FoodRatings(String[] foods, String[] cuisines, int[] ratings)` Initializes the syst... | null |
【Video】Give me 5 minutes - How we think about a solution | design-a-food-rating-system | 1 | 1 | # Intuition\nI like sushi.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/F6RAuglUOSg\n\n\u25A0 Timeline of the video\n\n`0:04` Explain constructor\n`1:21` Why -rating instead of rating?\n`4:09` Talk about changeRating\n`5:19` Time Complexity and Space Complexity\n`6:36` Step by step algorithm of my solution code\n`6:3... | 82 | Design a food rating system that can do the following:
* **Modify** the rating of a food item listed in the system.
* Return the highest-rated food item for a type of cuisine in the system.
Implement the `FoodRatings` class:
* `FoodRatings(String[] foods, String[] cuisines, int[] ratings)` Initializes the syst... | null |
Using maps || c++ || java || python | design-a-food-rating-system | 1 | 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\n Construction (__init__ method): O(N log M)\n\n N is the number of foods.\n M is the maximum number of foods for a parti... | 52 | Design a food rating system that can do the following:
* **Modify** the rating of a food item listed in the system.
* Return the highest-rated food item for a type of cuisine in the system.
Implement the `FoodRatings` class:
* `FoodRatings(String[] foods, String[] cuisines, int[] ratings)` Initializes the syst... | null |
Python3 Solution | design-a-food-rating-system | 0 | 1 | \n```\nfrom sortedcontainers import SortedList\nclass FoodRatings:\n\n def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):\n self.ratings={}\n self.cuisine={}\n self.by_cuisine=collections.defaultdict(lambda:SortedList())\n for food,cuisine,rating in zip(foods,c... | 5 | Design a food rating system that can do the following:
* **Modify** the rating of a food item listed in the system.
* Return the highest-rated food item for a type of cuisine in the system.
Implement the `FoodRatings` class:
* `FoodRatings(String[] foods, String[] cuisines, int[] ratings)` Initializes the syst... | null |
Short and Intuitive Python solution | design-a-food-rating-system | 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 | Design a food rating system that can do the following:
* **Modify** the rating of a food item listed in the system.
* Return the highest-rated food item for a type of cuisine in the system.
Implement the `FoodRatings` class:
* `FoodRatings(String[] foods, String[] cuisines, int[] ratings)` Initializes the syst... | null |
Heap-Based Solution (Python) | design-a-food-rating-system | 0 | 1 | # Code\n```\nfrom heapq import heappush, heappop\nfrom collections import defaultdict\n\nclass FoodRatings:\n\n def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):\n self._cuisines = cuisines\n self._ratings = ratings\n self._heaps = defaultdict(list)\n for i, (... | 1 | Design a food rating system that can do the following:
* **Modify** the rating of a food item listed in the system.
* Return the highest-rated food item for a type of cuisine in the system.
Implement the `FoodRatings` class:
* `FoodRatings(String[] foods, String[] cuisines, int[] ratings)` Initializes the syst... | null |
python | O(nlogn) sorting + binary search solution explained | number-of-excellent-pairs | 0 | 1 | For me, the key insight into this problem was the realization that the test we were provided to determine if a pair is excellent can be greatly simplified. The alternate test the simplification leads to can then be reverse to quickly construct and count excellent pairs.\n\n## Checking if a Pair is Excellent\nBefore dis... | 4 | You are given a **0-indexed** positive integer array `nums` and a positive integer `k`.
A pair of numbers `(num1, num2)` is called **excellent** if the following conditions are satisfied:
* **Both** the numbers `num1` and `num2` exist in the array `nums`.
* The sum of the number of set bits in `num1 OR num2` and ... | When should you use your armor ability? It is always optimal to use your armor ability on the level where you take the most amount of damage. |
[Python3] Sorting Hamming Weights + Binary Search With Detailed Explanations | number-of-excellent-pairs | 0 | 1 | I have to say that the problem description is a little bit confusing, so let\'s clarify it together.\n\n**Observations & Explanations**\n1. The problem asks for the number of **distinct** excellent pairs, therefore duplicated `num` in the `nums` array does not matter and we only need to look at unique `num` appeared in... | 22 | You are given a **0-indexed** positive integer array `nums` and a positive integer `k`.
A pair of numbers `(num1, num2)` is called **excellent** if the following conditions are satisfied:
* **Both** the numbers `num1` and `num2` exist in the array `nums`.
* The sum of the number of set bits in `num1 OR num2` and ... | When should you use your armor ability? It is always optimal to use your armor ability on the level where you take the most amount of damage. |
Python Solution | Brute Force | Optimized | O(N) | number-of-excellent-pairs | 0 | 1 | ```\nclass Solution:\n def countExcellentPairs(self, nums: List[int], k: int) -> int:\n count=0\n n=len(nums)\n \n # Brute Force\n # s=set()\n # for i in range(n):\n # for j in range(n):\n # a=nums[i] | nums[j]\n # b=nums[i] & nums[j]... | 1 | You are given a **0-indexed** positive integer array `nums` and a positive integer `k`.
A pair of numbers `(num1, num2)` is called **excellent** if the following conditions are satisfied:
* **Both** the numbers `num1` and `num2` exist in the array `nums`.
* The sum of the number of set bits in `num1 OR num2` and ... | When should you use your armor ability? It is always optimal to use your armor ability on the level where you take the most amount of damage. |
Python Simple Solution | number-of-excellent-pairs | 0 | 1 | ```\nclass Solution:\n def countExcellentPairs(self, nums: List[int], k: int) -> int:\n nums.sort()\n mapp = defaultdict(set)\n ans = 0\n last = None\n for i in nums:\n if i==last:\n continue\n b = format(i,\'b\').count(\'1\')\n mapp[... | 2 | You are given a **0-indexed** positive integer array `nums` and a positive integer `k`.
A pair of numbers `(num1, num2)` is called **excellent** if the following conditions are satisfied:
* **Both** the numbers `num1` and `num2` exist in the array `nums`.
* The sum of the number of set bits in `num1 OR num2` and ... | When should you use your armor ability? It is always optimal to use your armor ability on the level where you take the most amount of damage. |
Make Array Zero by Subtracting ... | make-array-zero-by-subtracting-equal-amounts | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis is just a greedy approach as they said to pick an element which should be minimum ...\nSort the input array and then decrement the corresponding value everytime in the array and then continue the process till it gets zero..\n\n# Code\n```\nclas... | 1 | You are given a non-negative integer array `nums`. In one operation, you must:
* Choose a positive integer `x` such that `x` is less than or equal to the **smallest non-zero** element in `nums`.
* Subtract `x` from every **positive** element in `nums`.
Return _the **minimum** number of operations to make every el... | null |
Take it easy!! | make-array-zero-by-subtracting-equal-amounts | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to find the minimum number of operations to make all elements in the given list unique. The operations involve removing duplicates and the number zero.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTh... | 2 | You are given a non-negative integer array `nums`. In one operation, you must:
* Choose a positive integer `x` such that `x` is less than or equal to the **smallest non-zero** element in `nums`.
* Subtract `x` from every **positive** element in `nums`.
Return _the **minimum** number of operations to make every el... | null |
Set | make-array-zero-by-subtracting-equal-amounts | 0 | 1 | Each unique number (except 0) needs one operation.\n\n**Python 3**\n```python\nclass Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n return len(set(nums) - {0})\n```\n**C++**\n```cpp\nint minimumOperations(vector<int>& nums) {\n return set<int>(begin(nums), end(nums)).size() - (count(beg... | 28 | You are given a non-negative integer array `nums`. In one operation, you must:
* Choose a positive integer `x` such that `x` is less than or equal to the **smallest non-zero** element in `nums`.
* Subtract `x` from every **positive** element in `nums`.
Return _the **minimum** number of operations to make every el... | null |
Beginner-friendly || Simple solution with Binary Search in Python3 / TypeScript | maximum-number-of-groups-entering-a-competition | 0 | 1 | # Intuition\nThe problem description is the following:\n- there\'s a list of students with `grades`\n- our goal find the **maximum count of student groups**\n\nThe groups need to follow these rules:\n1. `i` group must have size **less** than in `i+1` group\n2. sum of `grades` in `i` group must be **less** that in `i+1`... | 1 | You are given a positive integer array `grades` which represents the grades of students in a university. You would like to enter **all** these students into a competition in **ordered** non-empty groups, such that the ordering meets the following conditions:
* The sum of the grades of students in the `ith` group is ... | null |
[Python] Group students into groups of 1,2,3 ... K | Concise Solution | maximum-number-of-groups-entering-a-competition | 0 | 1 | # Intuition\nThe 2 constraints given are that each group should have more students than the previous group and the sum of grades should be more. \n\nIf we group students into groups of 1,2,3...K on a sorted array, that should take care of both the conditions. We don\'t need to explicitly sort it as we don\'t need to ou... | 1 | You are given a positive integer array `grades` which represents the grades of students in a university. You would like to enter **all** these students into a competition in **ordered** non-empty groups, such that the ordering meets the following conditions:
* The sum of the grades of students in the `ith` group is ... | null |
Python 3 O(N) | maximum-number-of-groups-entering-a-competition | 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(N) and \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity h... | 1 | You are given a positive integer array `grades` which represents the grades of students in a university. You would like to enter **all** these students into a competition in **ordered** non-empty groups, such that the ordering meets the following conditions:
* The sum of the grades of students in the `ith` group is ... | null |
✅Python || Math || Two Easy Approaches | maximum-number-of-groups-entering-a-competition | 0 | 1 | Math:\nWe have x students.\nThere are 1 student in 1st group,\n\t\t\t\t2 students in 2nd group,\n\t\t\t\t3 students in 3rd group,\n\t\t\t\t4 students in 4th group,\n\t\t\t\t...\n\t\t\t\tn students in n-th group\n\t\t\t\nWe have n * (n + 1) / 2 students in the first n groups totally,\nwe have (n + 1) * (n + 2) / 2 stude... | 4 | You are given a positive integer array `grades` which represents the grades of students in a university. You would like to enter **all** these students into a competition in **ordered** non-empty groups, such that the ordering meets the following conditions:
* The sum of the grades of students in the `ith` group is ... | null |
Straighforward python code (no algorithms) beats >90% | find-closest-node-to-given-two-nodes | 0 | 1 | # Intuition\nPretty straightforward. Im still new to algorithms, so I thought I would brute force it.\n\n# Approach\nKeep 2 SETS (or lists) to record the nodes travelled by nodes 1 and 2. \n\n-If any of the nodes\' value is in **its** set, it means it has been to this exact point before and thus is following a cyclic p... | 3 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from `i... | null |
Python sol with DFS and Defaultdict | find-closest-node-to-given-two-nodes | 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 a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from `i... | null |
📌Python3 || ⚡915 ms, faster than 98.28% of Python3 | find-closest-node-to-given-two-nodes | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:\n curr = [(node1 , 1), (node2 , 2)]\n v = [0] * len(edges)\n node = inf \n while curr:\n new = []\n f = False\n for a,w in curr:\n ... | 1 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from `i... | null |
A 2 pass solution in Python (BFS + loop once to find common nodes) | find-closest-node-to-given-two-nodes | 0 | 1 | # Intuition\n1. Problem refers to graph (probably BFS/DFS solution)\n2. Mention of only one direction outedge clarifies we don\'t need to search for multiple paths\n3. What we are trying to find here is essentially a mid-point between 2 nodes. \n4. Two options\n- Do the 2 pass solution outlined below\n- Start search fr... | 1 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from `i... | null |
Python BFS solution Fully Commented | find-closest-node-to-given-two-nodes | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nUse **Breadth First Search** twice to figure out the minimum distance from both ```node1``` and ```node2``` to every node.\n# Complexity\nLet $$n$$ be the number of nodes.\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$... | 1 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from `i... | null |
EASY PYTHON SOLUTION || BFS TRAVERSAL | find-closest-node-to-given-two-nodes | 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 a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from `i... | null |
Python3 || Beats 91.90% || Short solution | longest-cycle-in-a-graph | 0 | 1 | \n# Please UPVOTE\uD83D\uDE0A\n\n## Python3\n```\nclass Solution:\n def longestCycle(self, edges: List[int]) -> int:\n n=len(edges)\n bl=[0]*n\n mp=defaultdict(int)\n mx=-1\n ... | 24 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from no... | null |
simple solution using arival time. | longest-cycle-in-a-graph | 0 | 1 | \n```\nclass Solution:\n def longestCycle(self, edges: List[int]) -> int:\n v=[0]*len(edges)\n ans=-1\n for i in range(len(edges)):\n t=1\n c=i\n while c>=0:\n if v[c]!=0:\n if v[c][0]==i:\n ans=max(ans,t-v... | 2 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from no... | null |
[Python3] Really fast! Easy to Understand!!! Untraditional DFS | longest-cycle-in-a-graph | 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 a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from no... | null |
Python iterative BFS Solution | O(n) solution | longest-cycle-in-a-graph | 0 | 1 | ```\n def longestCycle(self, edges: List[int]) -> int:\n dq = deque();\n res,n = 0,len(edges) \n visitedglobal = [ 0 for i in range(0,n)]\n visited = defaultdict(int)\n for i in range(0,n):\n if(visitedglobal[i] == 0 and edges[i] != -1 ):\n visited.clear()\n ... | 1 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from no... | null |
[Python] Topological Sort, Daily Challenge Mar., day 26 | longest-cycle-in-a-graph | 0 | 1 | # Intuition\nuse topological sort to remove outermost nodes step by step,\nwe remove outermost node by setting **edges[outermost_node] = -1**\n\nthen, we can iterate `edges` again and union remain connected components\n\n- if every connected component\'s size is 1, it means there is NO cycle\n- else we just return max ... | 1 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from no... | null |
python3 Solution | longest-cycle-in-a-graph | 0 | 1 | \n```\nclass Solution:\n def longestCycle(self, edges: List[int]) -> int:\n n=len(edges)\n visit=set()\n ranks=[float(\'inf\')]*n\n\n def t(i,rank):\n if i in visit or edges[i]==-1:\n return -1\n\n if ranks[i]<rank:\n return rank-ranks[i... | 1 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from no... | null |
[Python 3] Kahn's Algorithm | longest-cycle-in-a-graph | 0 | 1 | ```\nclass Solution:\n def longestCycle(self, edges: List[int]) -> int:\n n = len(edges)\n indeg = Counter(edges)\n\n stack = [node for node in range(n) if indeg[node] == 0]\n inCycle = {node for node in range(n)}\n\n while stack:\n cur = stack.pop()\n inCycle... | 5 | You are given a **directed** graph of `n` nodes numbered from `0` to `n - 1`, where each node has **at most one** outgoing edge.
The graph is represented with a given **0-indexed** array `edges` of size `n`, indicating that there is a directed edge from node `i` to node `edges[i]`. If there is no outgoing edge from no... | null |
Hashmap Python3 | merge-similar-items | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n a, c, b = defaultdict(int), [], items1 + items2\n for j in b:\n if j[0] not in a: a[j[0]] = j[1]\n else: a[j[0]] = a[j[0]] + j[1]\n for i... | 1 | You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties:
* `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **weight** of the `ith` item.
* The value of each item in `items` is **u... | null |
Simple solution. Beats 100% in Python Using hash map. | merge-similar-items | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a hash map from the first array. (value: ... | 0 | You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties:
* `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **weight** of the `ith` item.
* The value of each item in `items` is **u... | null |
[Java/Python 3] TreeMap, w/ brief explanation and analysis. | merge-similar-items | 1 | 1 | Use TreeMap to accumulate the weights of items with same value.\n\n```java\n public List<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) {\n TreeMap<Integer, Integer> cnt = new TreeMap<>();\n for (int[] it : items1) {\n cnt.merge(it[0], it[1], Integer::sum);\n }\n ... | 32 | You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties:
* `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **weight** of the `ith` item.
* The value of each item in `items` is **u... | null |
Python Easy Solution | merge-similar-items | 0 | 1 | # Code\n```\nclass Solution:\n def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n items1.sort()\n items2.sort()\n res=[]\n i,j=0,0\n while(i<len(items1) and j<len(items2)):\n if items1[i][0]==items2[j][0]:\n ... | 1 | You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties:
* `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **weight** of the `ith` item.
* The value of each item in `items` is **u... | null |
[ Python ] ✅✅ Simple Python Solution Using HashMap 🥳✌👍 | merge-similar-items | 0 | 1 | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 138 ms, faster than 15.38% of Python3 online submissions for Merge Similar Items.\n# Memory Usage: 14.8 MB, less than 53.85% of Python3 online submissions for Merge Similar Items.\n\n\tclass Solution:\n\t\tdef me... | 11 | You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties:
* `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **weight** of the `ith` item.
* The value of each item in `items` is **u... | null |
✅Python || Easy Approaches | merge-similar-items | 0 | 1 | ```\nclass Solution:\n def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n \n \n hashset = {}\n\n for i in range(len(items1)):\n if items1[i][0] in hashset:\n hashset[items1[i][0]] += items1[i][1]\n else:... | 5 | You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties:
* `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **weight** of the `ith` item.
* The value of each item in `items` is **u... | null |
One Liner | merge-similar-items | 0 | 1 | **Python 3**\n```python\nclass Solution:\n def mergeSimilarItems(self, i1: List[List[int]], i2: List[List[int]]) -> List[List[int]]:\n return sorted((Counter({i[0] : i[1] for i in i1}) + Counter({i[0] : i[1] for i in i2})).items())\n``` | 10 | You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties:
* `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **weight** of the `ith` item.
* The value of each item in `items` is **u... | null |
Python one-line solution but extremely slow | merge-similar-items | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsed a bunch of list comprensions\n\n# Code\n```\nclass Solution:\n def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n return sorted([[v1, w1 + w2] for v1, w1 in items1 for v2, w2... | 1 | You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties:
* `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **weight** of the `ith` item.
* The value of each item in `items` is **u... | null |
BASIC APPROACH || BRUTE FORCE || PYTHON3 | merge-similar-items | 0 | 1 | # BASIC APPROACH || BRUTE FORCE || PYTHON3\n\n# Code\n```\nclass Solution:\n def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n ans=[]\n dicc={}\n\n for i in range(len(items1)):\n if items1[i][0] not in dicc:\n dicc[items... | 1 | You are given two 2D integer arrays, `items1` and `items2`, representing two sets of items. Each array `items` has the following properties:
* `items[i] = [valuei, weighti]` where `valuei` represents the **value** and `weighti` represents the **weight** of the `ith` item.
* The value of each item in `items` is **u... | null |
🔥 Python || Detailed Explanation ✅ || Faster Than 100% ✅|| Less than 100% ✅ || Simple || MATH | count-number-of-bad-pairs | 0 | 1 | **Appreciate if you could upvote this solution**\n\n\nMethod: `math`\n\nFirst, we know that the number of pair combinations for nums is `nCr`\nAlso, the condition can transform from `i-j != num[j]-num[i]` to `num[i]-i != num[j]-j` via basic calculation.\nThus, the result should be `nCr - num_of_pairs(num[i]-i == num[j]... | 39 | You are given a **0-indexed** integer array `nums`. A pair of indices `(i, j)` is a **bad pair** if `i < j` and `j - i != nums[j] - nums[i]`.
Return _the total number of **bad pairs** in_ `nums`.
**Example 1:**
**Input:** nums = \[4,1,3,3\]
**Output:** 5
**Explanation:** The pair (0, 1) is a bad pair since 1 - 0 != ... | null |
[Java/Python 3] Count good pairs, w/ brief explanation and analysis. | count-number-of-bad-pairs | 1 | 1 | \nGood pairs have same `nums[i] - i` value, so we can use HashMap to count the number of elements with same hash, `nums[i] - i`, then count the good pairs; Then use total pairs minus good pairs.\n\n```java\n public long countBadPairs(int[] nums) {\n long n = nums.length;\n Map<Integer, Integer> good = ... | 5 | You are given a **0-indexed** integer array `nums`. A pair of indices `(i, j)` is a **bad pair** if `i < j` and `j - i != nums[j] - nums[i]`.
Return _the total number of **bad pairs** in_ `nums`.
**Example 1:**
**Input:** nums = \[4,1,3,3\]
**Output:** 5
**Explanation:** The pair (0, 1) is a bad pair since 1 - 0 != ... | null |
✅Python || O(n) || Count || Easy Approaches | count-number-of-bad-pairs | 0 | 1 | ```\nclass Solution:\n def countBadPairs(self, nums: List[int]) -> int:\n\n n = len(nums)\n res = []\n for i in range(n):\n res.append(nums[i] - i)\n\n a = Counter(res)\n ans = n * (n - 1) // 2\n for x in a:\n if a[x] > 1:\n ans -= a[x] *... | 2 | You are given a **0-indexed** integer array `nums`. A pair of indices `(i, j)` is a **bad pair** if `i < j` and `j - i != nums[j] - nums[i]`.
Return _the total number of **bad pairs** in_ `nums`.
**Example 1:**
**Input:** nums = \[4,1,3,3\]
**Output:** 5
**Explanation:** The pair (0, 1) is a bad pair since 1 - 0 != ... | null |
Prettie prettie... prettie good solution in Python. | task-scheduler-ii | 0 | 1 | # Intuition\nKeep a dictionary of the format `{task: earliest day it can be completed}`. \nIterate through `tasks` and increment the current `day` by 1. \n\n# Approach\nIterate thru the list `tasks`. You can consider one task per day. \nIf `day` is behind the earliest day you can complete the `task`, then fast forward... | 1 | You are given a **0-indexed** array of positive integers `tasks`, representing tasks that need to be completed **in order**, where `tasks[i]` represents the **type** of the `ith` task.
You are also given a positive integer `space`, which represents the **minimum** number of days that must pass **after** the completion... | null |
Python || Easily Understood ✅ || Faster Than 98% || Simple || O(n) | task-scheduler-ii | 0 | 1 | ```\nimport math\nclass Solution:\n def taskSchedulerII(self, tasks: List[int], space: int) -> int:\n count_dict = {}\n total_days = 0\n for task in tasks:\n if task not in count_dict:\n count_dict[task] = -math.inf\n total_days = max(total_days + 1, count_di... | 19 | You are given a **0-indexed** array of positive integers `tasks`, representing tasks that need to be completed **in order**, where `tasks[i]` represents the **type** of the `ith` task.
You are also given a positive integer `space`, which represents the **minimum** number of days that must pass **after** the completion... | null |
✅Python || Easy Approach | task-scheduler-ii | 0 | 1 | ```\nclass Solution:\n def taskSchedulerII(self, tasks: List[int], space: int) -> int:\n \n ans = 0\n hashset = {}\n n = len(tasks)\n \n for x in set(tasks):\n hashset[x] = 0\n \n i = 0\n while i <= n - 1:\n flag = ans - hashset... | 2 | You are given a **0-indexed** array of positive integers `tasks`, representing tasks that need to be completed **in order**, where `tasks[i]` represents the **type** of the `ith` task.
You are also given a positive integer `space`, which represents the **minimum** number of days that must pass **after** the completion... | null |
[Java/Python 3] Use HashMap to store task and next available day, w/ brief explanation and analysis. | task-scheduler-ii | 1 | 1 | Traverse `tasks`, for each task `t`, compute the days needed and update the next available day for `t`.\n\n```java\n public long taskSchedulerII(int[] tasks, int space) {\n Map<Integer, Long> nextAvailableDay = new HashMap<>();\n long days = 0;\n for (int t : tasks) {\n days = Math.ma... | 13 | You are given a **0-indexed** array of positive integers `tasks`, representing tasks that need to be completed **in order**, where `tasks[i]` represents the **type** of the `ith` task.
You are also given a positive integer `space`, which represents the **minimum** number of days that must pass **after** the completion... | null |
【Video】Beat 99% solution with Python, JavaScript, Java and C++ | minimum-replacements-to-sort-the-array | 1 | 1 | # Intuition\nThe most important point is to think about divisible case and not divisible case for number of elements. This Python solution beats 99%.\n\n---\n\n\n# Solution Video\n\n### Please subscribe to my channel from here. I have 252 videos as of August 30th, 2023.\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.c... | 15 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
C++/Python Math explains Greedy||beats 98.50% | minimum-replacements-to-sort-the-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOnly the number at the end of the array is surely unchanged. Use backward iteration. Compare the last & current numbers. Proceed the division\n$$\ncurr=q*last+r\n$$\nand compute the number of operations and update the value for last.\n# A... | 7 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
[Python] greedy O(n) explained | minimum-replacements-to-sort-the-array | 0 | 1 | When iterating from the back of the array, each encountered value should not exceed the previous one (the array should be non-decreasing). Once this condition fails, a correspodning number `n` should be divided into a sum of elements, each one not exceeding `m` (i.e., the previous element from the back). The minimal nu... | 7 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
Greedy Python Solution with Thought Process || One For Loop + Two If Statements | minimum-replacements-to-sort-the-array | 0 | 1 | # Code\n```\nclass Solution:\n def minimumReplacement(self, nums: List[int]) -> int:\n N = len(nums)\n splits = 0\n \n for idx in reversed(range(1, N)):\n left, curr = nums[idx - 1], nums[idx]\n \n if left > curr:\n quotient = left // curr\n... | 3 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
✅Easy to understand🔥||✅Full Explanation🔥Done in few steps🔥||O(n) Solution | minimum-replacements-to-sort-the-array | 1 | 1 | # Problem Understanding:\nThe problem requires us to determine the **minimum number of operations** needed to make an array **sorted** in non-decreasing order. Each operation involves **replacing** an element with **two elements** that sum to it.\n\n# Logic Used in the problem\nThe logic revolves around the idea of ite... | 330 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
Python3 Solution | minimum-replacements-to-sort-the-array | 0 | 1 | \n```\nclass Solution:\n def minimumReplacement(self, nums: List[int]) -> int:\n ans=0\n prev=10**9+1\n for x in nums[::-1]:\n d=ceil(x/prev)\n ans+=d-1\n prev=x//d\n\n return ans \n``` | 2 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
python3 solution | minimum-replacements-to-sort-the-array | 0 | 1 | # Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution:\n def minimumReplacement(self, nums: List[int]) -> int:\n res=0\n for i in range(len(nums)-2, -1, -1):\n if nums[i] <= nums[i+1]: continue\n # We are using ceiling division method to co... | 1 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
Python: Observation. How to reach the solution | minimum-replacements-to-sort-the-array | 0 | 1 | # Observation\nSearching the minimum cost with a constraint(non-decreasing order form) can be tackled with DP, BS(Binary Search), or Greedy. \n\nHowever, the absence of a clear boundary and the unsorted series(num) hint us that it\'s not a BS problem. Also, The lack of a clear monotonic order(must do A before B) within... | 1 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
✅Easy Solution🔥Python/C#/C++/Java/C🔥Explain Line by Line🔥 | minimum-replacements-to-sort-the-array | 1 | 1 | # Problem\n---\nThe problem statement describes an array manipulation task where you are given an array nums, and you can perform operations that involve replacing an element of the array with two elements that sum up to the original element. The goal is to sort the array in non-decreasing order using the minimum numbe... | 12 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
✅ 99.17% O(n) Greedy with Dynamic Upper Bound Adjustment | minimum-replacements-to-sort-the-array | 1 | 1 | # Interview Guide - Minimum Replacements to Sort the Array: \n\n## Problem Understanding\n\n**Description**: \nAt its core, this problem is an intricate dance between array manipulation and greedy optimization. You\'re handed an integer array `nums` and given the ability to perform a unique, transformative operation: ... | 47 | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... | null |
[Java/Python 3] HashSet O(n) codes w/ analysis. | number-of-arithmetic-triplets | 1 | 1 | Credit to **@dms6** for the improvement from 2 pass to 1 pass.\n\n```java\n public int arithmeticTriplets(int[] nums, int diff) {\n int cnt = 0;\n Set<Integer> seen = new HashSet<>();\n for (int num : nums) {\n if (seen.contains(num - diff) && seen.contains(num - diff * 2)) {\n ... | 75 | You are given a **0-indexed**, **strictly increasing** integer array `nums` and a positive integer `diff`. A triplet `(i, j, k)` is an **arithmetic triplet** if the following conditions are met:
* `i < j < k`,
* `nums[j] - nums[i] == diff`, and
* `nums[k] - nums[j] == diff`.
Return _the number of unique **arith... | null |
✅Python || Easy Approach | number-of-arithmetic-triplets | 0 | 1 | ```\nclass Solution:\n def arithmeticTriplets(self, nums: List[int], diff: int) -> int:\n \n ans = 0\n n = len(nums)\n for i in range(n):\n if nums[i] + diff in nums and nums[i] + 2 * diff in nums:\n ans += 1\n \n return ans\n``` | 37 | You are given a **0-indexed**, **strictly increasing** integer array `nums` and a positive integer `diff`. A triplet `(i, j, k)` is an **arithmetic triplet** if the following conditions are met:
* `i < j < k`,
* `nums[j] - nums[i] == diff`, and
* `nums[k] - nums[j] == diff`.
Return _the number of unique **arith... | null |
Python | Easy | O(n) Solution | number-of-arithmetic-triplets | 0 | 1 | ```\nclass Solution:\n def arithmeticTriplets(self, nums: List[int], diff: int) -> int:\n dict_ = {}\n for num in nums:\n dict_[num] = dict_.get(num,0) + 1 ##To keep the count of each num\'s occurence\n \n count = 0\n for num in nums:\n if dict_.get(num+diff) ... | 1 | You are given a **0-indexed**, **strictly increasing** integer array `nums` and a positive integer `diff`. A triplet `(i, j, k)` is an **arithmetic triplet** if the following conditions are met:
* `i < j < k`,
* `nums[j] - nums[i] == diff`, and
* `nums[k] - nums[j] == diff`.
Return _the number of unique **arith... | null |
Hashset n-diff and n-2*diff | number-of-arithmetic-triplets | 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 a **0-indexed**, **strictly increasing** integer array `nums` and a positive integer `diff`. A triplet `(i, j, k)` is an **arithmetic triplet** if the following conditions are met:
* `i < j < k`,
* `nums[j] - nums[i] == diff`, and
* `nums[k] - nums[j] == diff`.
Return _the number of unique **arith... | null |
FASTEST, EASY PYTHON SOLUTION | reachable-nodes-with-restrictions | 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: $$O(N+2E)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N*E)$$\n<!-- Add your space complexity... | 2 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given an integer array `restricted` which represents **r... | null |
Basic DFS with Restrictions!!😸 | reachable-nodes-with-restrictions | 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 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given an integer array `restricted` which represents **r... | null |
python -bfs solution | reachable-nodes-with-restrictions | 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 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given an integer array `restricted` which represents **r... | null |
Simple python BFS solution, beats 86.82% and memory beats 91.56% | reachable-nodes-with-restrictions | 0 | 1 | # Intuition\nBFS\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:\n adj_list = defaultdic... | 1 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given an integer array `restricted` which represents **r... | null |
[Java/Python 3] BFS and DFS codes w/ brief explanation and analysis. | reachable-nodes-with-restrictions | 1 | 1 | 1. Use a `HashSet` to hold the restricted nodes and then visited nodes; \n2. Do BFS/DFS to explore the tree, and upon completing exploration the `HashSet` contains all reachable and all restricted nodes. \n3. We can use the size of the restricted to deduct the size of `HashSet` to get the number of the reachable ones.\... | 17 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given an integer array `restricted` which represents **r... | null |
Python begineer friendly solution || Easy to understand || Recursive Solution | reachable-nodes-with-restrictions | 0 | 1 | ```\nclass Solution:\n def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:\n\t\t# stores final ans\n self.ans = 0\n\t\t\n\t\t# adjacency list for graph\n self.adj = [[] for i in range(n)]\n for pair in edges:\n self.adj[pair[0]].append(pair[1])\n ... | 1 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given an integer array `restricted` which represents **r... | null |
Python3 BFS and DFS | reachable-nodes-with-restrictions | 0 | 1 | BFS\n\n```python\n def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:\n\t\tgraph = defaultdict(list)\n visited = [False]*n\n queue = deque([0])\n res = 0\n \n for u in restricted:\n visited[u] = True\n \n for u,v in edge... | 2 | There is an undirected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given an integer array `restricted` which represents **r... | null |
🦀🐍🐹 Rust + Go + Python & DP | check-if-there-is-a-valid-partition-for-the-array | 0 | 1 | **Intuition** \uD83E\uDDE0\n\nHey folks! Ever tried to slice an array into special subarrays, where the magic rules are:\n\n1. Two identical numbers sitting side by side, chilling.\n2. Three identical numbers just hanging out together.\n3. Or, three numbers increasing by one - like they\'re climbing stairs!\n\nOur task... | 4 | You are given a **0-indexed** integer array `nums`. You have to partition the array into one or more **contiguous** subarrays.
We call a partition of the array **valid** if each of the obtained subarrays satisfies **one** of the following conditions:
1. The subarray consists of **exactly** `2` equal elements. For ex... | How can we use precalculation to efficiently calculate the average difference at an index? Create a prefix and/or suffix sum array. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.