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 |
|---|---|---|---|---|---|---|---|
🔥🔥EASY BEGINNER FRIENDLY SOLUTION USING FREQUENCY HASHMAP !! 🔥🔥 | check-if-number-has-equal-digit-count-and-digit-value | 0 | 1 | # Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def digitCount(self, num: str) -> bool:\n dic=Counter(num)\n c=0\n for i in range(len(num)):\n if dic[str(i)]==int(num[i]):\n c+=1\n ... | 2 | You are given a **0-indexed** string `num` of length `n` consisting of digits.
Return `true` _if for **every** index_ `i` _in the range_ `0 <= i < n`_, the digit_ `i` _occurs_ `num[i]` _times in_ `num`_, otherwise return_ `false`.
**Example 1:**
**Input:** num = "1210 "
**Output:** true
**Explanation:**
num\[0\] = ... | Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array. |
🔥[Python 3] 4 lines using dictionary, beats 97% 🥷🏼 | sender-with-largest-word-count | 0 | 1 | ```python3 []\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n d = defaultdict(int)\n for m, n in zip(messages, senders):\n d[n] += len(m.split())\n return max(d, key = lambda k: (d[k], k))\n``` | 3 | You have a chat log of `n` messages. You are given two string arrays `messages` and `senders` where `messages[i]` is a **message** sent by `senders[i]`.
A **message** is list of **words** that are separated by a single space with no leading or trailing spaces. The **word count** of a sender is the total number of **wo... | For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order. For negative numbers, the digits should be arranged in descending order. |
Python3 | Hash word count associated with a sender's name then return max | sender-with-largest-word-count | 0 | 1 | ```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n words_count = defaultdict(int)\n for m, person in zip(messages, senders):\n words_count[person] += len(m.split())\n \n max_len = max(words_count.values())\n \n ... | 1 | You have a chat log of `n` messages. You are given two string arrays `messages` and `senders` where `messages[i]` is a **message** sent by `senders[i]`.
A **message** is list of **words** that are separated by a single space with no leading or trailing spaces. The **word count** of a sender is the total number of **wo... | For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order. For negative numbers, the digits should be arranged in descending order. |
Easy Python Solution With Dictionary | sender-with-largest-word-count | 0 | 1 | ```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n d={}\n l=[]\n for i in range(len(messages)):\n if senders[i] not in d:\n d[senders[i]]=len(messages[i].split())\n else:\n d[senders[i]]+=len(me... | 7 | You have a chat log of `n` messages. You are given two string arrays `messages` and `senders` where `messages[i]` is a **message** sent by `senders[i]`.
A **message** is list of **words** that are separated by a single space with no leading or trailing spaces. The **word count** of a sender is the total number of **wo... | For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order. For negative numbers, the digits should be arranged in descending order. |
Very simple Python solution O(nlog(n)) | maximum-total-importance-of-roads | 0 | 1 | ```\nclass Solution:\n def maximumImportance(self, n: int, roads: List[List[int]]) -> int:\n Arr = [0] * n # i-th city has Arr[i] roads\n for A,B in roads:\n Arr[A] += 1 # Each road increase the road count\n Arr[B] += 1\n Arr.sort() # Cities with most road should receive ... | 20 | You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`.
You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road connecting cities `ai` and `bi`.
You need to assign each city with an integ... | Note that flipping a bit twice does nothing. In order to determine the value of a bit, consider how you can efficiently count the number of flips made on the bit since its latest update. |
Python3 | Easy understanding | Faster than 100% time and memory | maximum-total-importance-of-roads | 0 | 1 | **UPVOTE IF YOU LIKE IT**\n```\nclass Solution:\n def maximumImportance(self, n: int, roads: List[List[int]]) -> int:\n \n \'\'\'The main idea is to count the frequency of the cities connected to roads and then \n keep on assigning the integer value from one to n to each cities after sorting ... | 2 | You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`.
You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road connecting cities `ai` and `bi`.
You need to assign each city with an integ... | Note that flipping a bit twice does nothing. In order to determine the value of a bit, consider how you can efficiently count the number of flips made on the bit since its latest update. |
Python Easy Solution using Sort | maximum-total-importance-of-roads | 0 | 1 | The main idea is:\n1. Find the number of roads that are connecting to each city. Let\'s call it `degrees` \n2. Sort the `degrees` in ascending order such that the city is the least number of connecting roads comes to the top. This will be assigned the least score.\n3. Sum the importance of all the cities. The importanc... | 2 | You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`.
You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road connecting cities `ai` and `bi`.
You need to assign each city with an integ... | Note that flipping a bit twice does nothing. In order to determine the value of a bit, consider how you can efficiently count the number of flips made on the bit since its latest update. |
Python | Simple | Explained | 3 Lines | rearrange-characters-to-make-target-string | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nI approached this problem by dividing the count of letters in both given string and target string. I take the minimum of b because we need to get the maximum amount of target strings we can make that using minimum of one letter.\n\n# Example\ns : ilov... | 1 | You are given two **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
Easy Python solution with Counter() | rearrange-characters-to-make-target-string | 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 **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
Python | Easy Solution✅ | rearrange-characters-to-make-target-string | 0 | 1 | ```\ndef rearrangeCharacters(self, s: str, target: str) -> int:\n maxx = []\n for i in range(len(set(target))):\n t_count = target.count(target[i]) # count the no of occurrence of letter in target string\n s_count = s.count(target[i]) # count the no of occurrence of target letter in ... | 10 | You are given two **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
Python Two Liner Beats ~95% | rearrange-characters-to-make-target-string | 0 | 1 | ```\nclass Solution:\n def rearrangeCharacters(self, s: str, target: str) -> int:\n counter_s = Counter(s) \n return min(counter_s[c] // count for c,count in Counter(target).items())\n```\n\n**Time - O(n)\nSpace - O(n)**\n\n--- \n***Please upvote if you find it useful*** | 18 | You are given two **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
Python | Easy Solution | Loops | Hashmap | rearrange-characters-to-make-target-string | 0 | 1 | # Code\n```\nclass Solution:\n def rearrangeCharacters(self, s: str, target: str) -> int:\n hashmap = defaultdict(int)\n for i in s:\n hashmap[i] += 1\n count = 0\n flag = 0\n while True:\n if flag:\n break\n for i in target:\n ... | 4 | You are given two **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
✅ 96% || Python3 || Counter and calculation | rearrange-characters-to-make-target-string | 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 **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
Python, two Counters | rearrange-characters-to-make-target-string | 0 | 1 | ```\nclass Solution:\n def rearrangeCharacters(self, s: str, target: str) -> int:\n s = Counter(s)\n target = Counter(target)\n return min(s[c] // target[c] for c in target)\n``` | 2 | You are given two **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
Python | Stright Forward | rearrange-characters-to-make-target-string | 0 | 1 | ```\nclass Solution:\n def rearrangeCharacters(self, s: str, target: str) -> int:\n counter_s = Counter(s)\n res = float(\'inf\')\n for k, v in Counter(target).items():\n res = min(res, counter_s[k] // v)\n return res\n``` | 2 | You are given two **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
Two Counters | rearrange-characters-to-make-target-string | 0 | 1 | **Python 3**\n```python\nclass Solution:\n def rearrangeCharacters(self, s: str, target: str) -> int:\n cnt, cnt1 = Counter(s), Counter(target)\n return min(cnt[ch] // cnt1[ch] for ch in cnt1.keys())\n``` | 2 | You are given two **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
Simple Python solution | rearrange-characters-to-make-target-string | 0 | 1 | ```\nclass Solution:\n def rearrangeCharacters(self, s: str, target: str) -> int:\n freqs = {} # count the letter ffrequency of string s\n for char in s:\n freqs[char] = freqs.get(char,0) + 1\n \n freqTarget = {} # count the letter ffrequency of target s\n for c in ... | 3 | You are given two **0-indexed** strings `s` and `target`. You can take some letters from `s` and rearrange them to form new strings.
Return _the **maximum** number of copies of_ `target` _that can be formed by taking letters from_ `s` _and rearranging them._
**Example 1:**
**Input:** s = "ilovecodingonleetcode ", t... | What is the highest possible answer for a set of n points? The highest possible answer is n / 2 (rounded up). This is because you can cover at least two points with a line, and if n is odd, you need to add one extra line to cover the last point. Suppose you have a line covering two points, how can you quickly check if ... |
Simple Python with explanation | apply-discount-to-prices | 0 | 1 | ```\nclass Solution:\n def discountPrices(self, sentence: str, discount: int) -> str:\n s = sentence.split() # convert to List to easily update\n m = discount / 100 \n for i,word in enumerate(s):\n if word[0] == "$" and word[1:].isdigit(): # Check whether it is in correct format\n ... | 9 | A **sentence** is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign `'$'`. A word represents a **price** if it is a sequence of digits preceded by a dollar sign.
* For example, `"$100 "`, `"$23 "`, and `"$6 "` represent prices while `"100 "`, `"$ "`, ... | Try simulating the process until either of the two integers is zero. Count the number of operations done. |
Self Explanatory Python3 using startswith and string.split( | apply-discount-to-prices | 0 | 1 | \n# Code\n```\nclass Solution:\n def discountPrices(self, sentence: str, discount: int) -> str:\n words = sentence.split()\n for i, word in enumerate(words):\n if word.startswith(\'\n```) and word[1:].isdigit():\n price = int(word[1:])\n discounted_price = round... | 1 | A **sentence** is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign `'$'`. A word represents a **price** if it is a sequence of digits preceded by a dollar sign.
* For example, `"$100 "`, `"$23 "`, and `"$6 "` represent prices while `"100 "`, `"$ "`, ... | Try simulating the process until either of the two integers is zero. Count the number of operations done. |
Regex sub, 92% speed | apply-discount-to-prices | 0 | 1 | \n```\nfrom re import compile\nclass Solution:\n pat = compile(r"(?<= [$])(\\d+)(?= )")\n def discountPrices(self, sentence: str, discount: int) -> str:\n coeff = 1 - discount / 100\n return... | 0 | A **sentence** is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign `'$'`. A word represents a **price** if it is a sequence of digits preceded by a dollar sign.
* For example, `"$100 "`, `"$23 "`, and `"$6 "` represent prices while `"100 "`, `"$ "`, ... | Try simulating the process until either of the two integers is zero. Count the number of operations done. |
[Python3] Regex substitution | apply-discount-to-prices | 0 | 1 | ```python\nclass Solution:\n def discountPrices(self, sentence: str, discount: int) -> str:\n """If you use regex, now you have two problems. \n\n Lots of trial and error on regex101.com\n\n 254 ms, faster than 40.17%\n """\n \n def repl(m):\n rep = float(m.group(... | 1 | A **sentence** is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign `'$'`. A word represents a **price** if it is a sequence of digits preceded by a dollar sign.
* For example, `"$100 "`, `"$23 "`, and `"$6 "` represent prices while `"100 "`, `"$ "`, ... | Try simulating the process until either of the two integers is zero. Count the number of operations done. |
Python | Easy ✅ | apply-discount-to-prices | 0 | 1 | ```python\nclass Solution:\n def discountPrices(self, sentence: str, discount: int) -> str:\n words = sentence.split()\n calc_price = lambda cost, discount: cost * (discount / 100)\n\n for i, w in enumerate(words):\n if w.startswith("$"):\n price = w[1:]\n ... | 1 | A **sentence** is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign `'$'`. A word represents a **price** if it is a sequence of digits preceded by a dollar sign.
* For example, `"$100 "`, `"$23 "`, and `"$6 "` represent prices while `"100 "`, `"$ "`, ... | Try simulating the process until either of the two integers is zero. Count the number of operations done. |
Easy Python Solution | apply-discount-to-prices | 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 | A **sentence** is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign `'$'`. A word represents a **price** if it is a sequence of digits preceded by a dollar sign.
* For example, `"$100 "`, `"$23 "`, and `"$6 "` represent prices while `"100 "`, `"$ "`, ... | Try simulating the process until either of the two integers is zero. Count the number of operations done. |
2288. Apply Discount to Prices | apply-discount-to-prices | 0 | 1 | # Intuition\nThe array approach makes handling valid prices much easier compared to the iteration of the entire string. \n\n# Approach\n1. Split into array, elements with prices will be either valid or invalid \n2. Check whether it is a valid price by checking if element starts with `$`\nand whether the entire string a... | 0 | A **sentence** is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign `'$'`. A word represents a **price** if it is a sequence of digits preceded by a dollar sign.
* For example, `"$100 "`, `"$23 "`, and `"$6 "` represent prices while `"100 "`, `"$ "`, ... | Try simulating the process until either of the two integers is zero. Count the number of operations done. |
[Python3] Increasing Stack | steps-to-make-array-non-decreasing | 0 | 1 | Reverse scan from right to left, maintain an increasing stack.\nFor i<j and nums[i]>nums[j], the number of rounds for nums[i] to remove nums[j] is:\n 1. If nums[j] takes 3 rounds to remove all smaller numbers on its right, then it will also take nums[i] same 3 rounds to remove nums[j], not 1 round. \n 2. If nums[... | 14 | You are given a **0-indexed** integer array `nums`. In one step, **remove** all elements `nums[i]` where `nums[i - 1] > nums[i]` for all `0 < i < nums.length`.
Return _the number of steps performed until_ `nums` _becomes a **non-decreasing** array_.
**Example 1:**
**Input:** nums = \[5,3,4,4,7,3,6,11,8,5,11\]
**Outp... | Count the frequency of each element in odd positions in the array. Do the same for elements in even positions. To minimize the number of operations we need to maximize the number of elements we keep from the original array. What are the possible combinations of elements we can choose from odd indices and even indices s... |
Python3 easiest solution beats 90% | steps-to-make-array-non-decreasing | 0 | 1 | # Code\n```\nclass Solution:\n def totalSteps(self, A: List[int]) -> int: \n st = [[A[0], 0]]\n ans = 0\n \n for a in A[1:]:\n t = 0\n while st and st[-1][0] <= a:\n t = max(t, st[-1][1])\n st.pop()\n if st: \n ... | 2 | You are given a **0-indexed** integer array `nums`. In one step, **remove** all elements `nums[i]` where `nums[i - 1] > nums[i]` for all `0 < i < nums.length`.
Return _the number of steps performed until_ `nums` _becomes a **non-decreasing** array_.
**Example 1:**
**Input:** nums = \[5,3,4,4,7,3,6,11,8,5,11\]
**Outp... | Count the frequency of each element in odd positions in the array. Do the same for elements in even positions. To minimize the number of operations we need to maximize the number of elements we keep from the original array. What are the possible combinations of elements we can choose from odd indices and even indices s... |
Easy Python Linked List Simulation Solution | steps-to-make-array-non-decreasing | 0 | 1 | **Walkthrough**\nThis is def not as elegant as the DP solution. But personally I find it easier to understand and a little bit more intuitive. What it is is recognizing the fact that linked list can help us for this problem because we keep deleting adjacent elements. \n\nThere are mostly 3 steps:\n1. Convert the array ... | 3 | You are given a **0-indexed** integer array `nums`. In one step, **remove** all elements `nums[i]` where `nums[i - 1] > nums[i]` for all `0 < i < nums.length`.
Return _the number of steps performed until_ `nums` _becomes a **non-decreasing** array_.
**Example 1:**
**Input:** nums = \[5,3,4,4,7,3,6,11,8,5,11\]
**Outp... | Count the frequency of each element in odd positions in the array. Do the same for elements in even positions. To minimize the number of operations we need to maximize the number of elements we keep from the original array. What are the possible combinations of elements we can choose from odd indices and even indices s... |
Efficient Algorithm for Making an Array Non-Decreasing with Step-by-Step Visualization | steps-to-make-array-non-decreasing | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks us to find the minimum number of steps required to make the input array non-decreasing. One way to approach this problem is to keep track of the elements in the array that need to be removed in order to make it non-decrea... | 2 | You are given a **0-indexed** integer array `nums`. In one step, **remove** all elements `nums[i]` where `nums[i - 1] > nums[i]` for all `0 < i < nums.length`.
Return _the number of steps performed until_ `nums` _becomes a **non-decreasing** array_.
**Example 1:**
**Input:** nums = \[5,3,4,4,7,3,6,11,8,5,11\]
**Outp... | Count the frequency of each element in odd positions in the array. Do the same for elements in even positions. To minimize the number of operations we need to maximize the number of elements we keep from the original array. What are the possible combinations of elements we can choose from odd indices and even indices s... |
[Python 3] 0-1 BFS - Easy to understand | minimum-obstacle-removal-to-reach-corner | 0 | 1 | # Intuition\nFind the shortest path with the weight is only 0 or 1 => 0-1 BFS\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ncan refer 0-1 BFS [here](https://cp-algorithms.com/graph/01_bfs.html#algorithm)\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Ti... | 3 | You are given a **0-indexed** 2D integer array `grid` of size `m x n`. Each cell has one of two values:
* `0` represents an **empty** cell,
* `1` represents an **obstacle** that may be removed.
You can move up, down, left, or right from and to an empty cell.
Return _the **minimum** number of **obstacles** to **r... | Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans. Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans. Can we iterate over how many... |
[Java/Python 3] 2 codes: Shortest Path & BFS, w/ brief explanation, analysis and similar problems. | minimum-obstacle-removal-to-reach-corner | 1 | 1 | **Q & A**\n\nQ1: Why do we not need to keep track of which nodes we\'ve already visited? Is this code perhaps already implicitly tracking the nodes we\'ve visited? According to the implementation of Lazy Dijkstra [here](http://nmamano.com/blog/dijkstra/dijkstra.html), we need to keep track of which nodes we\'ve already... | 85 | You are given a **0-indexed** 2D integer array `grid` of size `m x n`. Each cell has one of two values:
* `0` represents an **empty** cell,
* `1` represents an **obstacle** that may be removed.
You can move up, down, left, or right from and to an empty cell.
Return _the **minimum** number of **obstacles** to **r... | Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans. Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans. Can we iterate over how many... |
[Python3] Dijkstra's algo | minimum-obstacle-removal-to-reach-corner | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/7a598e64fb507fc966a3025d8edd0c8e7caf0bec) for solutions of weekly 295. \n\n```\nclass Solution:\n def minimumObstacles(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n dist = [[inf]*n for _ in range(m)]\n ... | 1 | You are given a **0-indexed** 2D integer array `grid` of size `m x n`. Each cell has one of two values:
* `0` represents an **empty** cell,
* `1` represents an **obstacle** that may be removed.
You can move up, down, left, or right from and to an empty cell.
Return _the **minimum** number of **obstacles** to **r... | Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans. Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans. Can we iterate over how many... |
🔥[Python 3] Simple recursion with diapason pass | min-max-game | 0 | 1 | ```python3 []\nclass Solution:\n def minMaxGame(self, nums: List[int]) -> int:\n def getMinMax(l, r, func):\n if r - l == 1: return nums[l]\n mid = l + (r-l)//2\n return func(getMinMax(l, mid, min), getMinMax(mid, r, max))\n \n return getMinMax(0, len(nums), ... | 3 | You are given a **0-indexed** integer array `nums` whose length is a power of `2`.
Apply the following algorithm on `nums`:
1. Let `n` be the length of `nums`. If `n == 1`, **end** the process. Otherwise, **create** a new **0-indexed** integer array `newNums` of length `n / 2`.
2. For every **even** index `i` where... | Notice that for anagrams, the order of the letters is irrelevant. For each letter, we can count its frequency in s and t. For each letter, its contribution to the answer is the absolute difference between its frequency in s and t. |
✅ Python Easy Approach | min-max-game | 0 | 1 | ```\nclass Solution:\n def minMaxGame(self, nums: List[int]) -> int: \n l=nums\n while len(l)>1:\n is_min=True \n tmp=[]\n for i in range(0, len(l), 2):\n if is_min:\n tmp.append(min(l[i:i+2]))\n else:\... | 11 | You are given a **0-indexed** integer array `nums` whose length is a power of `2`.
Apply the following algorithm on `nums`:
1. Let `n` be the length of `nums`. If `n == 1`, **end** the process. Otherwise, **create** a new **0-indexed** integer array `newNums` of length `n / 2`.
2. For every **even** index `i` where... | Notice that for anagrams, the order of the letters is irrelevant. For each letter, we can count its frequency in s and t. For each letter, its contribution to the answer is the absolute difference between its frequency in s and t. |
✅ EASY SOLUTION PYTHON || BEATS 99% RUNTIME ✅ | min-max-game | 0 | 1 | Here: \n1. count is the counter inside a function set to maintain the max min pattern ( if count is odd => find min; else => find max)\n2. final [] returns the modified list with max min values as list values which replaces the nums\n3. repeating the process until we get only one element in nums\n# Code\n```\nclass Sol... | 2 | You are given a **0-indexed** integer array `nums` whose length is a power of `2`.
Apply the following algorithm on `nums`:
1. Let `n` be the length of `nums`. If `n == 1`, **end** the process. Otherwise, **create** a new **0-indexed** integer array `newNums` of length `n / 2`.
2. For every **even** index `i` where... | Notice that for anagrams, the order of the letters is irrelevant. For each letter, we can count its frequency in s and t. For each letter, its contribution to the answer is the absolute difference between its frequency in s and t. |
[Python 3] Sort + Greedy - Simple Solution | partition-array-such-that-maximum-difference-is-k | 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(NlogN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity ... | 3 | You are given an integer array `nums` and an integer `k`. You may partition `nums` into one or more **subsequences** such that each element in `nums` appears in **exactly** one of the subsequences.
Return _the **minimum** number of subsequences needed such that the difference between the maximum and minimum values in ... | For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search. |
Python Easy Solution using Sorting | partition-array-such-that-maximum-difference-is-k | 0 | 1 | ### Explanation:\n\nInitially I did think it as a DP problem because of the word "**subsequence**" and "**minimum**". But after analysing the array and output I realized we are more concerned about "**at most difference should be K**", and the at most difference is of min element and max element of subsequence, so what... | 22 | You are given an integer array `nums` and an integer `k`. You may partition `nums` into one or more **subsequences** such that each element in `nums` appears in **exactly** one of the subsequences.
Return _the **minimum** number of subsequences needed such that the difference between the maximum and minimum values in ... | For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search. |
Simple Python Solution | partition-array-such-that-maximum-difference-is-k | 0 | 1 | # Intuition\nSort Your given array. Why? Because we need to find subsequence so order isnt define for them.\nWe are asked to return minimum number of subsequence we need to form so our aim is to add as many number as possible in one array with limit(k).\n`How limit is defined? largest ele - Smallest ele`\nAs we sorted ... | 2 | You are given an integer array `nums` and an integer `k`. You may partition `nums` into one or more **subsequences** such that each element in `nums` appears in **exactly** one of the subsequences.
Return _the **minimum** number of subsequences needed such that the difference between the maximum and minimum values in ... | For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search. |
✅ Python Simple Map Approach | replace-elements-in-an-array | 0 | 1 | The core logic for this is the reversed iteration to construct the final replacements list.The reversed iteration helps to link the last replacement.\n\nThere can be chain of `operations` which will replace the same index in the array.\neg:\n> **operations = [[1,2], [2,3], [3,4]], nums = [1, 7, 9, 10]**\n\nIf you consi... | 29 | You are given a **0-indexed** array `nums` that consists of `n` **distinct** positive integers. Apply `m` operations to this array, where in the `ith` operation you replace the number `operations[i][0]` with `operations[i][1]`.
It is guaranteed that in the `ith` operation:
* `operations[i][0]` **exists** in `nums`.... | What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values? |
O(n) space, O(n) time solution using a map | replace-elements-in-an-array | 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 **0-indexed** array `nums` that consists of `n` **distinct** positive integers. Apply `m` operations to this array, where in the `ith` operation you replace the number `operations[i][0]` with `operations[i][1]`.
It is guaranteed that in the `ith` operation:
* `operations[i][0]` **exists** in `nums`.... | What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values? |
Python two solutions with explanation | replace-elements-in-an-array | 0 | 1 | **Solution 1: Index mapping**\nWe buid a hashmap that contains {value: index} key pairs. Based on the index looked up from that hashmap, for each operation, we update both the replaced value in nums, and the {updated num: index} key-value pair in the hashmap\nTotal runtime: `O(len(nums))` to build the hashmap + `O(len(... | 9 | You are given a **0-indexed** array `nums` that consists of `n` **distinct** positive integers. Apply `m` operations to this array, where in the `ith` operation you replace the number `operations[i][0]` with `operations[i][1]`.
It is guaranteed that in the `ith` operation:
* `operations[i][0]` **exists** in `nums`.... | What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values? |
✅ Python3 solution | replace-elements-in-an-array | 0 | 1 | ```\nclass Solution:\n def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:\n d = {} \n for i,num in enumerate(nums):\n d[num] = i #Save index of all elements in dictionary for O(1) lookup\n \n for x,r in operations:\n where = d[x] # Find... | 4 | You are given a **0-indexed** array `nums` that consists of `n` **distinct** positive integers. Apply `m` operations to this array, where in the `ith` operation you replace the number `operations[i][0]` with `operations[i][1]`.
It is guaranteed that in the `ith` operation:
* `operations[i][0]` **exists** in `nums`.... | What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values? |
✅Just String Slicing Nothing Else✅ | design-a-text-editor | 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. -->\nI also use "|" like the actual case, It helps you to understand Better.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n-... | 1 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
Simple O(k) Python solution in 11 lines of code, beats 95% | design-a-text-editor | 0 | 1 | # Complexity\n- Time complexities: $$\\begin{matrix}\n\\textrm{\\_\\_init\\_\\_} & \\mathcal O(1) \\\\\n\\textrm{addText} & \\mathcal O(len(text)) \\\\\n\\textrm{deleteText} & \\mathcal O(k) \\\\\n\\textrm{cursorLeft} & \\mathcal O(k) \\\\\n\\textrm{cursorRight} & \\mathcal O(k)\n\\end{matrix}$$\n\n<!-- Add your time c... | 1 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
Solution | design-a-text-editor | 1 | 1 | ```C++ []\nclass TextEditor {\npublic:\n string ltext = "", rtext="";\n TextEditor() {}\n \n void addText(string text) {\n ltext += text;\n }\n \n int deleteText(int k) {\n k = min(k, (int) ltext.size());\n ltext.resize(ltext.size() - k);\n return k;\n }\n \n st... | 27 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
Python 3 solution beat 95% using stack and queue | design-a-text-editor | 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)$$ -->\naddText: O(n)\ndeleteText: O(k)\ncursorLeft: O(k)\ncursorRight: O(k)\n- Spac... | 8 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
Python Easy Logical Starightforward | design-a-text-editor | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse python functions to manipulate strings\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe tricky part is to figure which index location is our cursor present..\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add... | 1 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
✅ Python Simple Solution | design-a-text-editor | 0 | 1 | The approach that I am using is string slicing. So that would end up with `O(n)` time for all the operations. The following implementation seems to pass without any TLE. I will update this post once I find a more optimized solution.\n\n```\nclass TextEditor:\n\n def __init__(self):\n self.s = \'\'\n s... | 20 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
[Python] Easy to Understand Solution String Operation | design-a-text-editor | 0 | 1 | ```\nclass TextEditor:\n\n def __init__(self):\n self.txt = \'\' \n self.ptr = 0 \n\n def addText(self, text: str) -> None:\n self.txt = self.txt[:self.ptr] + text + self.txt[self.ptr:]\n self.ptr += len(text) \n\n def deleteText(self, k: int) -> int:\n org = len(self.txt)... | 5 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
[Explained] Easy Python Solution using String slicing | design-a-text-editor | 0 | 1 | # [Explained] Easy Python Solution using String slicing\n\n```\nclass TextEditor:\n\n def __init__(self):\n """\n\t\tstring storage\n\t\t"""\n\t\tself.txt = \'\' \n\t\t\n\t\t"""\n\t\tcursor/pointer location storage\n\t\t"""\n self.ptr = 0 \n \n\n def addText(self, text: str) -> None:\n\t\t"... | 2 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
✅Python clean and easy solution: 2 stacks solution | design-a-text-editor | 0 | 1 | The idea is very simple: divide the text into two parts: left (text before the cursor) and right(text after the cursor)\n```\nclass TextEditor:\n\n def __init__(self):\n self.left = []\n self.right = []\n\n def addText(self, text: str) -> None:\n self.left.extend(text)\n\n def deleteText(s... | 6 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
Simple Python Solution - 2 stacks - O(K) time (where K<N), O(N) space complexity | design-a-text-editor | 0 | 1 | Basic idea:\n=====\n1. Create two stacks, left and right. The "left" stack is left of cursor, while the "right" stack is right of cursor.\n2. addText - we append characters to the "left" stack.\n3. deleteText - we delete text by popping characters from the "left" stack.\n4. cursorLeft - we move the cursor to the left b... | 11 | Design a text editor with a cursor that can do the following:
* **Add** text to where the cursor is.
* **Delete** text from where the cursor is (simulating the backspace key).
* **Move** the cursor either left or right.
When deleting text, only characters to the left of the cursor will be deleted. The cursor wi... | null |
[Java/Python 3] 2 codes w/ brief explanation and analysis. | strong-password-checker-ii | 1 | 1 | **Method 1: Use HashSet to count conditions**\n\n**Q & A**\n\nQ: Does the `HashSet` in the codes really cost space `O(1)`?\nA: Java `HashSet` is implemented on `HashMap`, which has an initial size of `16`. The size will not increase since the load factor `4 / 16 < 0.75`. Generally speaking, space `O(16) = O(1)`. \n\nIf... | 33 | A password is said to be **strong** if it satisfies all the following criteria:
* It has at least `8` characters.
* It contains at least **one lowercase** letter.
* It contains at least **one uppercase** letter.
* It contains at least **one digit**.
* It contains at least **one special character**. The speci... | How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes acros... |
Nothing Special | strong-password-checker-ii | 0 | 1 | We do not need to check for a special character. \n\nWe just count lowercase/uppercase letters and digits. The rest of the characters are special.\n\n**C++**\n```cpp\nbool strongPasswordCheckerII(string p) {\n int lo = 0, up = 0, digit = 0, sz = p.size();\n for (int i = 0; i < sz; ++i) {\n if (i > 0 && p[i... | 24 | A password is said to be **strong** if it satisfies all the following criteria:
* It has at least `8` characters.
* It contains at least **one lowercase** letter.
* It contains at least **one uppercase** letter.
* It contains at least **one digit**.
* It contains at least **one special character**. The speci... | How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes acros... |
[Python/Java/C++/C#/JavaScript/PHP] Regex | strong-password-checker-ii | 1 | 1 | ### Just for fun ( \u02C6_\u02C6 ) \u2013 [don\'t do regex](https://softwareengineering.stackexchange.com/questions/113237/when-you-should-not-use-regular-expressions) for interviews! \n\n1. Hyphen or minus sign `-` has to be placed at the end or at the begining of the character class (`[]`), for special chars (i.e., `... | 6 | A password is said to be **strong** if it satisfies all the following criteria:
* It has at least `8` characters.
* It contains at least **one lowercase** letter.
* It contains at least **one uppercase** letter.
* It contains at least **one digit**.
* It contains at least **one special character**. The speci... | How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes acros... |
Python | Easy Solution✅ | strong-password-checker-ii | 0 | 1 | ```\ndef strongPasswordCheckerII(self, password: str) -> bool:\n if len(password) < 8:\n return False\n lowercase, uppercase, digit, special = False, False, False, False\n special_char = "!@#$%^&*()-+"\n for i in range(len(password)):\n if i != len(password)-1 and passw... | 7 | A password is said to be **strong** if it satisfies all the following criteria:
* It has at least `8` characters.
* It contains at least **one lowercase** letter.
* It contains at least **one uppercase** letter.
* It contains at least **one digit**.
* It contains at least **one special character**. The speci... | How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes acros... |
Easy Python Solution (using count approach) | strong-password-checker-ii | 0 | 1 | ```\ndef strongPasswordCheckerII(self, password: str) -> bool:\n u,l,d,s=0,0,0,0\n if len(password)<8: return False\n for i in range(0,len(password)):\n if i>0 and password[i-1]==password[i]: return False\n if password[i].isdigit(): d+=1\n elif password[i].islower()... | 5 | A password is said to be **strong** if it satisfies all the following criteria:
* It has at least `8` characters.
* It contains at least **one lowercase** letter.
* It contains at least **one uppercase** letter.
* It contains at least **one digit**.
* It contains at least **one special character**. The speci... | How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes acros... |
Python, regex, easy to understand | strong-password-checker-ii | 0 | 1 | bool(re.search(r"(.)\\1+", s)) --> backreference in regex to check if two adjacent chars are equal or not.\n```\nimport re\nclass Solution:\n def strongPasswordCheckerII(self, s: str) -> bool:\n \n if len(s)<8:\n return False\n \n if (bool(re.search(r\'[a-z]\',s)) and \n ... | 2 | A password is said to be **strong** if it satisfies all the following criteria:
* It has at least `8` characters.
* It contains at least **one lowercase** letter.
* It contains at least **one uppercase** letter.
* It contains at least **one digit**.
* It contains at least **one special character**. The speci... | How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes acros... |
Simple Python Code | Binary Search | successful-pairs-of-spells-and-potions | 0 | 1 | # Approach: `Binary Search`\n\n# Complexity\n- Time complexity: `O(N LogN)`\n\n- Space complexity: ` O(N) `\n\n# Code\n```\nclass Solution:\n def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:\n potions.sort()\n x = []\n for i in spells:\n l,r... | 1 | You are given two positive integer arrays `spells` and `potions`, of length `n` and `m` respectively, where `spells[i]` represents the strength of the `ith` spell and `potions[j]` represents the strength of the `jth` potion.
You are also given an integer `success`. A spell and potion pair is considered **successful** ... | Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character. |
Clear Python Solution--Using Binary Search | successful-pairs-of-spells-and-potions | 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 integer arrays `spells` and `potions`, of length `n` and `m` respectively, where `spells[i]` represents the strength of the `ith` spell and `potions[j]` represents the strength of the `jth` potion.
You are also given an integer `success`. A spell and potion pair is considered **successful** ... | Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character. |
Python solution | successful-pairs-of-spells-and-potions | 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 integer arrays `spells` and `potions`, of length `n` and `m` respectively, where `spells[i]` represents the strength of the `ith` spell and `potions[j]` represents the strength of the `jth` potion.
You are also given an integer `success`. A spell and potion pair is considered **successful** ... | Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character. |
Python O(mlogn) solution for reference | successful-pairs-of-spells-and-potions | 0 | 1 | \n# Code\n```\nclass Solution:\n def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:\n # We find the lowest value of potion that is needed for\n # a spell to be sucess, that is \'x\' here\n # now we can sort the potions, search for the value\n # ju... | 1 | You are given two positive integer arrays `spells` and `potions`, of length `n` and `m` respectively, where `spells[i]` represents the strength of the `ith` spell and `potions[j]` represents the strength of the `jth` potion.
You are also given an integer `success`. A spell and potion pair is considered **successful** ... | Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character. |
Easy Python Solution for beginners | successful-pairs-of-spells-and-potions | 0 | 1 | # Code\n```\nclass Solution:\n def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:\n def binary_search(temp,m,target):\n l = 0\n r = m-1\n while l < r:\n mid = l + (r-l)//2\n if temp[mid] >= target:\n ... | 1 | You are given two positive integer arrays `spells` and `potions`, of length `n` and `m` respectively, where `spells[i]` represents the strength of the `ith` spell and `potions[j]` represents the strength of the `jth` potion.
You are also given an integer `success`. A spell and potion pair is considered **successful** ... | Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character. |
o(1) space solution beats 100% space and 100% time | successful-pairs-of-spells-and-potions | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nsimply use sort potions and use binary search.\n# Complexity\n- Time complexity:\nO(nlog(n)+m)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nimport bisect\nclass Solution:\n def successfulPairs(self, spells: List[int], pot... | 1 | You are given two positive integer arrays `spells` and `potions`, of length `n` and `m` respectively, where `spells[i]` represents the strength of the `ith` spell and `potions[j]` represents the strength of the `jth` potion.
You are also given an integer `success`. A spell and potion pair is considered **successful** ... | Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character. |
✅ Python Precalculation O(n*k) without TLE | match-substring-after-replacement | 0 | 1 | I have added comments to help understand better. I have seen many python solutions getting TLE. To avoid that, I have added a precalculation logic. Please let me know if there is a better way. :)\n\n```\nclass Solution:\n def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:\n s_map... | 7 | You are given two strings `s` and `sub`. You are also given a 2D character array `mappings` where `mappings[i] = [oldi, newi]` indicates that you may perform the following operation **any** number of times:
* **Replace** a character `oldi` of `sub` with `newi`.
Each character in `sub` **cannot** be replaced more th... | For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers... |
[Python3] Easy to understand Solution using Dictionary and HashSet | match-substring-after-replacement | 0 | 1 | ```\nclass Solution:\n def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:\n dic = {}\n for m in mappings:\n if m[0] not in dic:\n dic[m[0]] = {m[1]}\n else:\n dic[m[0]].add(m[1])\n \n for i in range(len(s)-l... | 4 | You are given two strings `s` and `sub`. You are also given a 2D character array `mappings` where `mappings[i] = [oldi, newi]` indicates that you may perform the following operation **any** number of times:
* **Replace** a character `oldi` of `sub` with `newi`.
Each character in `sub` **cannot** be replaced more th... | For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers... |
[Python 3]KMP Algorithm | match-substring-after-replacement | 0 | 1 | \n```\nclass Solution:\n def matchReplacement(self, s: str, p: str, mappings: List[List[str]]) -> bool:\n m = defaultdict(set)\n for a, b in mappings:\n m[a].add(b) \n \n\t\t# build pattern array\n i, j = 0, 1\n arr = [0] * len(p)\n while j < len(p):\n ... | 0 | You are given two strings `s` and `sub`. You are also given a 2D character array `mappings` where `mappings[i] = [oldi, newi]` indicates that you may perform the following operation **any** number of times:
* **Replace** a character `oldi` of `sub` with `newi`.
Each character in `sub` **cannot** be replaced more th... | For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers... |
Sliding Window | count-subarrays-with-score-less-than-k | 1 | 1 | This problem is similar to [713. Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/).\n\nWe use a sliding window technique, tracking the sum of the subarray in the window.\n\nThe score of the subarray in the window is `sum * (i - j + 1)`. We move the left side of the window, decre... | 133 | The **score** of an array is defined as the **product** of its sum and its length.
* For example, the score of `[1, 2, 3, 4, 5]` is `(1 + 2 + 3 + 4 + 5) * 5 = 75`.
Given a positive integer array `nums` and an integer `k`, return _the **number of non-empty subarrays** of_ `nums` _whose score is **strictly less** tha... | null |
[Java/Python 3] Sliding window T O(n) S O(1) code w/ brief explanation and analysis. | count-subarrays-with-score-less-than-k | 1 | 1 | Similar Problems and study materials on leedcode:\n\n[Sliding Window Problems](https://leetcode.com/tag/sliding-window/)\n[Sliding Window for Beginners [Problems | Template | Sample Solutions]](https://leetcode.com/discuss/general-discussion/657507/Sliding-Window-for-Beginners-Problems-or-Template-or-Sample-Solutions)\... | 7 | The **score** of an array is defined as the **product** of its sum and its length.
* For example, the score of `[1, 2, 3, 4, 5]` is `(1 + 2 + 3 + 4 + 5) * 5 = 75`.
Given a positive integer array `nums` and an integer `k`, return _the **number of non-empty subarrays** of_ `nums` _whose score is **strictly less** tha... | null |
[Python3] bracket by bracket | calculate-amount-paid-in-taxes | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/e59b5d5832483707a595ae92b9aa1fb456986009) for solutions of weekly 297\n\n```\nclass Solution:\n def calculateTax(self, brackets: List[List[int]], income: int) -> float:\n ans = prev = 0 \n for hi, pct in brackets: \n hi ... | 15 | You are given a **0-indexed** 2D integer array `brackets` where `brackets[i] = [upperi, percenti]` means that the `ith` tax bracket has an upper bound of `upperi` and is taxed at a rate of `percenti`. The brackets are **sorted** by upper bound (i.e. `upperi-1 < upperi` for `0 < i < brackets.length`).
Tax is calculated... | With the constraints, could we try every substring? Yes, checking every substring has runtime O(n^2), which will pass. How can we make sure we only count unique substrings? Use a set to store previously counted substrings. Hashing a string s of length m takes O(m) time. Is there a fast way to compute the hash of s if w... |
[Java/Python 3] Simple O(n) codes. | calculate-amount-paid-in-taxes | 1 | 1 | ```java\n public double calculateTax(int[][] brackets, int income) {\n double tax = 0;\n int prev = 0;\n for (int[] bracket : brackets) {\n int upper = bracket[0], percent = bracket[1];\n if (income >= upper) {\n tax += (upper - prev) * percent / 100d;\n ... | 33 | You are given a **0-indexed** 2D integer array `brackets` where `brackets[i] = [upperi, percenti]` means that the `ith` tax bracket has an upper bound of `upperi` and is taxed at a rate of `percenti`. The brackets are **sorted** by upper bound (i.e. `upperi-1 < upperi` for `0 < i < brackets.length`).
Tax is calculated... | With the constraints, could we try every substring? Yes, checking every substring has runtime O(n^2), which will pass. How can we make sure we only count unique substrings? Use a set to store previously counted substrings. Hashing a string s of length m takes O(m) time. Is there a fast way to compute the hash of s if w... |
Python Doesn't get any easier than this | calculate-amount-paid-in-taxes | 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 **0-indexed** 2D integer array `brackets` where `brackets[i] = [upperi, percenti]` means that the `ith` tax bracket has an upper bound of `upperi` and is taxed at a rate of `percenti`. The brackets are **sorted** by upper bound (i.e. `upperi-1 < upperi` for `0 < i < brackets.length`).
Tax is calculated... | With the constraints, could we try every substring? Yes, checking every substring has runtime O(n^2), which will pass. How can we make sure we only count unique substrings? Use a set to store previously counted substrings. Hashing a string s of length m takes O(m) time. Is there a fast way to compute the hash of s if w... |
Simple Python Solution | calculate-amount-paid-in-taxes | 0 | 1 | ```\nclass Solution:\n def calculateTax(self, brackets: List[List[int]], income: int) -> float:\n brackets.sort(key=lambda x: x[0])\n res = 0 # Total Tax \n prev = 0 # Prev Bracket Upperbound\n for u, p in brackets:\n if income >= u: # \n res += ((u-prev) * p) / ... | 2 | You are given a **0-indexed** 2D integer array `brackets` where `brackets[i] = [upperi, percenti]` means that the `ith` tax bracket has an upper bound of `upperi` and is taxed at a rate of `percenti`. The brackets are **sorted** by upper bound (i.e. `upperi-1 < upperi` for `0 < i < brackets.length`).
Tax is calculated... | With the constraints, could we try every substring? Yes, checking every substring has runtime O(n^2), which will pass. How can we make sure we only count unique substrings? Use a set to store previously counted substrings. Hashing a string s of length m takes O(m) time. Is there a fast way to compute the hash of s if w... |
Python3 solution | Easy to understand | concise and simple code | | calculate-amount-paid-in-taxes | 0 | 1 | ```\nclass Solution:\n def calculateTax(self, brackets: List[List[int]], income: int) -> float:\n lower = 0; \n\t\ttax = 0; \n\t\tleft = income # amount left to be taxed\n for i in brackets:\n k = i[0]-lower # amount being taxed\n if k<= left:\n tax+=k*i[1]/100; le... | 1 | You are given a **0-indexed** 2D integer array `brackets` where `brackets[i] = [upperi, percenti]` means that the `ith` tax bracket has an upper bound of `upperi` and is taxed at a rate of `percenti`. The brackets are **sorted** by upper bound (i.e. `upperi-1 < upperi` for `0 < i < brackets.length`).
Tax is calculated... | With the constraints, could we try every substring? Yes, checking every substring has runtime O(n^2), which will pass. How can we make sure we only count unique substrings? Use a set to store previously counted substrings. Hashing a string s of length m takes O(m) time. Is there a fast way to compute the hash of s if w... |
Python || Simple 6-Liner | calculate-amount-paid-in-taxes | 0 | 1 | ```\nclass Solution:\n def calculateTax(self, l: List[List[int]], k: int) -> float:\n prev=sol=0\n for x,y in l:\n t, prev = min(x,k)-prev, x\n if t<0:break\n sol+=t*y/100\n return sol\n```\n\n**Happy Coding !!** | 1 | You are given a **0-indexed** 2D integer array `brackets` where `brackets[i] = [upperi, percenti]` means that the `ith` tax bracket has an upper bound of `upperi` and is taxed at a rate of `percenti`. The brackets are **sorted** by upper bound (i.e. `upperi-1 < upperi` for `0 < i < brackets.length`).
Tax is calculated... | With the constraints, could we try every substring? Yes, checking every substring has runtime O(n^2), which will pass. How can we make sure we only count unique substrings? Use a set to store previously counted substrings. Hashing a string s of length m takes O(m) time. Is there a fast way to compute the hash of s if w... |
O(n) Solution in python | calculate-amount-paid-in-taxes | 0 | 1 | ```\n\t\tleng = len(brackets)\n\t\t\'\'\' if income is 0, no tax \'\'\'\n if income == 0:\n return float(0)\n \n tax = 0\n\t\t\'\'\' here we calculate tax for 1st bracket i.e. at index \'\'\'\n if (income > brackets[0][0]):\n tax = brackets[0][0] * (brackets[0][1] * 0.... | 1 | You are given a **0-indexed** 2D integer array `brackets` where `brackets[i] = [upperi, percenti]` means that the `ith` tax bracket has an upper bound of `upperi` and is taxed at a rate of `percenti`. The brackets are **sorted** by upper bound (i.e. `upperi-1 < upperi` for `0 < i < brackets.length`).
Tax is calculated... | With the constraints, could we try every substring? Yes, checking every substring has runtime O(n^2), which will pass. How can we make sure we only count unique substrings? Use a set to store previously counted substrings. Hashing a string s of length m takes O(m) time. Is there a fast way to compute the hash of s if w... |
Python Recursion + Memoization | minimum-path-cost-in-a-grid | 0 | 1 | **Observations:**\n1. This problem can be solved using recursion but simple recursion will lead to TLE.\n2. If we make the recursion tree we can easily see that we will have a lot of redundant computations.\n\n**For this example: *grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]***\n![im... | 13 | You are given a **0-indexed** `m x n` integer matrix `grid` consisting of **distinct** integers from `0` to `m * n - 1`. You can move in this matrix from a cell to any other cell in the **next** row. That is, if you are in cell `(x, y)` such that `x < m - 1`, you can move to any of the cells `(x + 1, 0)`, `(x + 1, 1)`,... | From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order. |
[Java/Python 3] 2 DP codes: space O(m * n) and O(n), w/ analysis. | minimum-path-cost-in-a-grid | 1 | 1 | ```java\n public int minPathCost(int[][] grid, int[][] moveCost) {\n int m = grid.length, n = grid[0].length;\n int[][] cost = new int[m][n];\n for (int c = 0; c < n; ++c) {\n cost[0][c] = grid[0][c];\n }\n for (int r = 1; r < m; ++r) {\n for (int c = 0; c < n... | 24 | You are given a **0-indexed** `m x n` integer matrix `grid` consisting of **distinct** integers from `0` to `m * n - 1`. You can move in this matrix from a cell to any other cell in the **next** row. That is, if you are in cell `(x, y)` such that `x < m - 1`, you can move to any of the cells `(x + 1, 0)`, `(x + 1, 1)`,... | From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order. |
Python | Memoization | minimum-path-cost-in-a-grid | 0 | 1 | ```\nclass Solution:\n def minPathCost(self, grid: list[list[int]], moveCost: list[list[int]]) -> int:\n\n @lru_cache()\n def helper(i, j):\n if i >= len(grid) - 1:\n return grid[i][j]\n \n m_cost = 9999999999\n cost = 0\n\n for k in... | 11 | You are given a **0-indexed** `m x n` integer matrix `grid` consisting of **distinct** integers from `0` to `m * n - 1`. You can move in this matrix from a cell to any other cell in the **next** row. That is, if you are in cell `(x, y)` such that `x < m - 1`, you can move to any of the cells `(x + 1, 0)`, `(x + 1, 1)`,... | From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order. |
[Python3] top-down dp | minimum-path-cost-in-a-grid | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/e59b5d5832483707a595ae92b9aa1fb456986009) for solutions of weekly 297\n\n```\nclass Solution:\n def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n @cache\n ... | 7 | You are given a **0-indexed** `m x n` integer matrix `grid` consisting of **distinct** integers from `0` to `m * n - 1`. You can move in this matrix from a cell to any other cell in the **next** row. That is, if you are in cell `(x, y)` such that `x < m - 1`, you can move to any of the cells `(x + 1, 0)`, `(x + 1, 1)`,... | From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order. |
Python3 Solution | fair-distribution-of-cookies | 0 | 1 | \n```\nclass Solution:\n def distributeCookies(self, cookies: List[int], k: int) -> int:\n n=len(cookies)\n\n @cache\n def fn(mask,k):\n if mask==0:\n return 0\n\n if k==0:\n return inf\n\n ans=inf\n orig=mask\n\n ... | 2 | You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The **unfair... | The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums. |
Best Solution | fair-distribution-of-cookies | 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$$O(n*2^k)$$\n\n\n# Code\n```\nclass Solution:\n def solve(self,index,buc... | 1 | You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The **unfair... | The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums. |
EASY PYTHON SOLUTION USING BACKTRACKING AND DP | fair-distribution-of-cookies | 0 | 1 | # Code\n```\nclass Solution: \n def dp(self,i,dist,cookies,k,dct):\n if i<0:\n return max(dist)\n if (i,tuple(dist)) in dct:\n return dct[(i,tuple(dist))]\n ans=float("infinity")\n for j in range(k):\n dist[j]+=cookies[i]\n if max(dist)<ans:\n ... | 1 | You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The **unfair... | The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums. |
Python optimization needed to avoid TLE | fair-distribution-of-cookies | 0 | 1 | # Intuition\nSince data size is small, just brutal force it using backtracking; however, for python3 time constraint is tight. \n\nTo make it work, each time I sort the current count for each child to break symmetry of the state. For example, if we have 2 children and 30 candies, then allocation (10, 20) equal (20, 10)... | 1 | You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The **unfair... | The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums. |
Python short and clean. Backtracking. DFS. | fair-distribution-of-cookies | 0 | 1 | # Approach\nTL;DR, Similar to [Editorial Solution](https://leetcode.com/problems/fair-distribution-of-cookies/editorial/) with an additional `average` based pruning.\n\n# Complexity\n- Time complexity: $$O(k^n)$$\n\n- Space complexity: $$O(k + n)$$\n\nwhere, `n is number of cookies(bags)`.\n\n# Code\n```python\nclass S... | 2 | You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The **unfair... | The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums. |
Python3 easy solution | naming-a-company | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n- make array of size 26*26.\n- i will represent first incident alphabet of ideas.\n- j will be our replacement for i alphabet.\n- value of $$match[i][j]$$ will decide that how many times replacing current idea\'s incident with another word\'s incident... | 3 | You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
1. Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2. Swap the first letters of `ideaA` and `ideaB` with each other.
3. If ... | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. |
Python3 👍||⚡96/98 T/M beats, only 10 lines 🔥|| Optimization Simple explain ||attach a TLE solution | naming-a-company | 0 | 1 | \n\n# Approach\nCreate Hash table with \nkey: > prefix_word , in other words words[0]\nvalue: > suffux_word , in other words words[1:]\n<!-- Describe your approach to solving the problem. -->\n\n# Complexit... | 2 | You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
1. Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2. Swap the first letters of `ideaA` and `ideaB` with each other.
3. If ... | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. |
O(n) | O(n) | Python Solution | Explained | naming-a-company | 0 | 1 | Hello **Tenno Leetcoders**, \n\nFor this problem, we are giving an array of strings `ideas`, we want to return `valid distinct names for companies`\n\nThe restrictions are as follows:\n1) If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separ... | 1 | You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
1. Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2. Swap the first letters of `ideaA` and `ideaB` with each other.
3. If ... | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. |
Python 11 lines, faster than 98% | naming-a-company | 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\nTODO\n<!-- - Time complexity: -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n\n# Code\n`... | 1 | You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
1. Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2. Swap the first letters of `ideaA` and `ideaB` with each other.
3. If ... | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. |
Python3 dictionary solution 96.74% | naming-a-company | 0 | 1 | # Idea\nConstruct a dictionary `d` with keys the alphabats `x` where the values are set of strings `s` such that `x+s` is in `ideas`. One can then derive the result by computing pairwise intersections.\n\n# Code\n```\nclass Solution:\n def distinctNames(self, ideas: List[str]) -> int:\n d = defaultdict(set)\n... | 1 | You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
1. Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2. Swap the first letters of `ideaA` and `ideaB` with each other.
3. If ... | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. |
🐸Python|| begineer friendly|| well explained | naming-a-company | 0 | 1 | # Intitution\nElement with same first letter cannot form valid combination as replecing them create the same name again.\nTherefore, there is no relation between element with same first letter. So, we will divide them into different set with same first letter.\nThen we will compare every set and and check the common el... | 1 | You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
1. Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2. Swap the first letters of `ideaA` and `ideaB` with each other.
3. If ... | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. |
Hash - beating 95% in speed | naming-a-company | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe length of ideas is at 10^4 level, which means we cannot just loop twice, as the limit is at 10^6 level. \nGiven we need to find the unoverlapped rest of strings other than the initial, we can use hash - to keep the length of substring... | 1 | You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
1. Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2. Swap the first letters of `ideaA` and `ideaB` with each other.
3. If ... | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. |
Counter | greatest-english-letter-in-upper-and-lower-case | 0 | 1 | **Python 3**\n```python\nclass Solution:\n def greatestLetter(self, s: str) -> str:\n cnt = Counter(s)\n return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), "")\n```\n**C++**\n```cpp\nstring greatestLetter(string s) {\n int cnt[128] = {};\n for (auto ch : s)\n ... | 46 | Given a string of English letters `s`, return _the **greatest** English letter which occurs as **both** a lowercase and uppercase letter in_ `s`. The returned letter should be in **uppercase**. If no such letter exists, return _an empty string_.
An English letter `b` is **greater** than another letter `a` if `b` appea... | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. |
Python Elegant & Short | 98.51% faster | Two solutions | O(n*log(n)) and O(n) | greatest-english-letter-in-upper-and-lower-case | 0 | 1 | \n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(2*26*log(2*26))\n\t\tMemory: O(2*26)\n\t\t"""\n\n\t\tdef greatestLetter(self, s: str) -> str:\n\t\t\tletters = set(s)\n\n\t\t\tfor ltr in sorted(letters, reverse=Tru... | 2 | Given a string of English letters `s`, return _the **greatest** English letter which occurs as **both** a lowercase and uppercase letter in_ `s`. The returned letter should be in **uppercase**. If no such letter exists, return _an empty string_.
An English letter `b` is **greater** than another letter `a` if `b` appea... | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. |
Python || Hash Map || O(N) || Easy Solution | greatest-english-letter-in-upper-and-lower-case | 0 | 1 | # Code\n```\nclass Solution:\n def greatestLetter(self, s: str) -> str:\n dic={}\n res=""\n for i in s:\n if i>=\'A\' and i<=\'Z\':\n if i in dic and dic[i]%2==1:\n dic[i]+=2\n elif i not in dic:\n dic[i]=2\n ... | 2 | Given a string of English letters `s`, return _the **greatest** English letter which occurs as **both** a lowercase and uppercase letter in_ `s`. The returned letter should be in **uppercase**. If no such letter exists, return _an empty string_.
An English letter `b` is **greater** than another letter `a` if `b` appea... | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. |
Python 1-liner | greatest-english-letter-in-upper-and-lower-case | 0 | 1 | The intersection between the uppercase and lowercase string results the characters of interest.\n\n```\nclass Solution:\n def greatestLetter(self, s: str) -> str:\n return max(Counter(s) & Counter(s.swapcase()), default="").upper()\n``` | 1 | Given a string of English letters `s`, return _the **greatest** English letter which occurs as **both** a lowercase and uppercase letter in_ `s`. The returned letter should be in **uppercase**. If no such letter exists, return _an empty string_.
An English letter `b` is **greater** than another letter `a` if `b` appea... | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. |
Simple Python 2-liner | greatest-english-letter-in-upper-and-lower-case | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def greatestLetter(self, s: str) -> str:\n a = [x for x in s if x.upper() in s and x.lower() in s] + [""]\n return max(a).upper()\n```\n | 3 | Given a string of English letters `s`, return _the **greatest** English letter which occurs as **both** a lowercase and uppercase letter in_ `s`. The returned letter should be in **uppercase**. If no such letter exists, return _an empty string_.
An English letter `b` is **greater** than another letter `a` if `b` appea... | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. |
Easy python solution | greatest-english-letter-in-upper-and-lower-case | 0 | 1 | ```\ndef greatestLetter(self, s: str) -> str:\n c="abcdefghijklmnopqrstuvwxyz"\n l=[""]\n for i in c:\n if i in s and i.upper() in s:\n l.append(i.upper())\n l.sort()\n return l[-1]\n``` | 2 | Given a string of English letters `s`, return _the **greatest** English letter which occurs as **both** a lowercase and uppercase letter in_ `s`. The returned letter should be in **uppercase**. If no such letter exists, return _an empty string_.
An English letter `b` is **greater** than another letter `a` if `b` appea... | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. |
Python Math Solution | Only Looking at Unit Digit | Clean & Concise | sum-of-numbers-with-units-digit-k | 0 | 1 | ```\nclass Solution:\n def minimumNumbers(self, num: int, k: int) -> int:\n if num == 0:\n return 0\n unit = num % 10\n for i in range(1, 11):\n if (i * k) % 10 == unit:\n if i * k <= num:\n return i\n else:\n ... | 1 | Given two integers `num` and `k`, consider a set of positive integers with the following properties:
* The units digit of each integer is `k`.
* The sum of the integers is `num`.
Return _the **minimum** possible size of such a set, or_ `-1` _if no such set exists._
Note:
* The set can contain multiple instanc... | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. |
Python solution | Constant Time-Complexity | Simple Solution | No DP nor Greedy | | sum-of-numbers-with-units-digit-k | 0 | 1 | The Approach is quite simple, You\'ve to understand that inorder to get the sum "num" from numbers ending with digit "k", you need to check the last digit of the multiple of the "k" upto 10 and these digits will repeat after 10 again. so if the ending digit exists in the dictionary of "k"s multiples that means the sum ... | 1 | Given two integers `num` and `k`, consider a set of positive integers with the following properties:
* The units digit of each integer is `k`.
* The sum of the integers is `num`.
Return _the **minimum** possible size of such a set, or_ `-1` _if no such set exists._
Note:
* The set can contain multiple instanc... | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. |
O(1) Python | sum-of-numbers-with-units-digit-k | 0 | 1 | ```\n\tdef minimumNumbers(self, num: int, k: int) -> int:\n t = num%10\n if num==0:\n return 0\n if num<k:\n return -1\n for i in range(1,11):\n if (i*k)%10 == t:\n if i*k <= num:\n return i\n return -1\n``` | 1 | Given two integers `num` and `k`, consider a set of positive integers with the following properties:
* The units digit of each integer is `k`.
* The sum of the integers is `num`.
Return _the **minimum** possible size of such a set, or_ `-1` _if no such set exists._
Note:
* The set can contain multiple instanc... | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.