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 |
|---|---|---|---|---|---|---|---|
Is Array Sorted and Rotated, Python code made easy | check-if-array-is-sorted-and-rotated | 0 | 1 | ```\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n count = 0\n for i in range(len(nums) - 1):\n if nums[i] > nums[i+1]:\n count += 1\n \n if nums[0] < nums[len(nums)-1]:\n count += 1\n \n return count <= 1\n``` | 4 | You are given an `m x n` integer matrix `grid`.
A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus ... | Brute force and check if it is possible for a sorted array to start from each position. |
😎 Find no. of break Points || O(n) FAANG 🥳 Optimized Code💥 | check-if-array-is-sorted-and-rotated | 1 | 1 | # \uD83D\uDDEF\uFE0FIntuition :-\n<!-- Describe your first thoughts on how to solve this problem. -->\nif array is sorted and rotated then, there is only 1 break point where (nums[x] > nums[x+1]),\nif array is only sorted then, there is 0 break point.\n\n# ***Please do Upvote \u270C\uFE0F***\n\n# \uD83D\uDDEF\uFE0FComp... | 34 | Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`.
There may be **duplicates** in the original array.
**Note:** An array `A` rotated by `x` positions results in an array `B` of the sa... | To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arith... |
😎 Find no. of break Points || O(n) FAANG 🥳 Optimized Code💥 | check-if-array-is-sorted-and-rotated | 1 | 1 | # \uD83D\uDDEF\uFE0FIntuition :-\n<!-- Describe your first thoughts on how to solve this problem. -->\nif array is sorted and rotated then, there is only 1 break point where (nums[x] > nums[x+1]),\nif array is only sorted then, there is 0 break point.\n\n# ***Please do Upvote \u270C\uFE0F***\n\n# \uD83D\uDDEF\uFE0FComp... | 34 | You are given an `m x n` integer matrix `grid`.
A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus ... | Brute force and check if it is possible for a sorted array to start from each position. |
Easy deque solution- Beats 98% others | check-if-array-is-sorted-and-rotated | 0 | 1 | \n# Code\n```\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n queue =deque(nums)\n for i in range(len(nums)):\n queue.rotate(1)\n if list(queue)==sorted(nums):\n return True\n``` | 1 | Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`.
There may be **duplicates** in the original array.
**Note:** An array `A` rotated by `x` positions results in an array `B` of the sa... | To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arith... |
Easy deque solution- Beats 98% others | check-if-array-is-sorted-and-rotated | 0 | 1 | \n# Code\n```\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n queue =deque(nums)\n for i in range(len(nums)):\n queue.rotate(1)\n if list(queue)==sorted(nums):\n return True\n``` | 1 | You are given an `m x n` integer matrix `grid`.
A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus ... | Brute force and check if it is possible for a sorted array to start from each position. |
Basic Implementation with clear approach | Detailed | check-if-array-is-sorted-and-rotated | 0 | 1 | Time Complexity: O(N)\nSpace Complexity: O(1)\n\n# Approach and Implementation\nTo implement a solution for this problem, you should be aware of what happens when you rotate a sorted array.\n\nLook at the image below. We have a sorted and rotated array:\n_. Otherwise, return `false`.
There may be **duplicates** in the original array.
**Note:** An array `A` rotated by `x` positions results in an array `B` of the sa... | To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arith... |
Basic Implementation with clear approach | Detailed | check-if-array-is-sorted-and-rotated | 0 | 1 | Time Complexity: O(N)\nSpace Complexity: O(1)\n\n# Approach and Implementation\nTo implement a solution for this problem, you should be aware of what happens when you rotate a sorted array.\n\nLook at the image below. We have a sorted and rotated array:\n to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. |
Simple solution with Heap/Priority Queue in Python3 | maximum-score-from-removing-stones | 0 | 1 | # Intuition\nHere we have:\n- three integers `a, b, c` respectively\n- our goal is to achieve **maximum score** from decrementing these integers\n\nThere\'re some rules to decrement them:\n- at each step you should take 2 integers and decrement **both**\n- the process repeats until you have **two values == 0**\n\nPresu... | 1 | You are given two integer arrays `nums1` and `nums2` of length `n`.
The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**).
* For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) +... | It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation |
Easy Approach using Max Heap !! | maximum-score-from-removing-stones | 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 playing a solitaire game with **three piles** of stones of sizes `a`, `b`, and `c` respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there ar... | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. |
Easy Approach using Max Heap !! | maximum-score-from-removing-stones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | You are given two integer arrays `nums1` and `nums2` of length `n`.
The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**).
* For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) +... | It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation |
one liner . in O(1) time ans space | maximum-score-from-removing-stones | 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:1\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:1\n<!-- Add your space complexity here, e.g. $$O(n)$$ ... | 9 | You are playing a solitaire game with **three piles** of stones of sizes `a`, `b`, and `c` respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there ar... | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. |
one liner . in O(1) time ans space | maximum-score-from-removing-stones | 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:1\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:1\n<!-- Add your space complexity here, e.g. $$O(n)$$ ... | 9 | You are given two integer arrays `nums1` and `nums2` of length `n`.
The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**).
* For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) +... | It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation |
Rutime - 100% beats 💥 || Memory ~ 100% beats 💥 || Fully Explained ✅ || Python ✅ || Java ✅ | maximum-score-from-removing-stones | 1 | 1 | # Approach\n\nThe given approach calculates the maximum score that can be obtained in a solitaire game with three piles of stones, represented by `a`, `b`, and `c`.\n\n1. Calculate the total sum of `a`, `b`, and `c` as `n = a + b + c`. This step determines the total number of stones in the game.\n\n2. Find the maximum ... | 3 | You are playing a solitaire game with **three piles** of stones of sizes `a`, `b`, and `c` respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there ar... | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. |
Rutime - 100% beats 💥 || Memory ~ 100% beats 💥 || Fully Explained ✅ || Python ✅ || Java ✅ | maximum-score-from-removing-stones | 1 | 1 | # Approach\n\nThe given approach calculates the maximum score that can be obtained in a solitaire game with three piles of stones, represented by `a`, `b`, and `c`.\n\n1. Calculate the total sum of `a`, `b`, and `c` as `n = a + b + c`. This step determines the total number of stones in the game.\n\n2. Find the maximum ... | 3 | You are given two integer arrays `nums1` and `nums2` of length `n`.
The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**).
* For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) +... | It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation |
[Python3] math | maximum-score-from-removing-stones | 0 | 1 | \n```\nclass Solution:\n def maximumScore(self, a: int, b: int, c: int) -> int:\n a, b, c = sorted((a, b, c))\n if a + b < c: return a + b\n return (a + b + c)//2\n``` | 18 | You are playing a solitaire game with **three piles** of stones of sizes `a`, `b`, and `c` respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there ar... | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. |
[Python3] math | maximum-score-from-removing-stones | 0 | 1 | \n```\nclass Solution:\n def maximumScore(self, a: int, b: int, c: int) -> int:\n a, b, c = sorted((a, b, c))\n if a + b < c: return a + b\n return (a + b + c)//2\n``` | 18 | You are given two integer arrays `nums1` and `nums2` of length `n`.
The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**).
* For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) +... | It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation |
[Python3] greedy | largest-merge-of-two-strings | 0 | 1 | **Algo**\nDefine two pointers `i1` and `i2` for `word1` and `word2` respectively. Pick word from `word1` iff `word1[i1:] > word2[i2]`.\n\n**Implementation**\n```\nclass Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n ans = []\n i1 = i2 = 0\n while i1 < len(word1) and i2 < le... | 6 | You are given two strings `word1` and `word2`. You want to construct a string `merge` in the following way: while either `word1` or `word2` are non-empty, choose **one** of the following options:
* If `word1` is non-empty, append the **first** character in `word1` to `merge` and delete it from `word1`.
* For e... | null |
[Python3] greedy | largest-merge-of-two-strings | 0 | 1 | **Algo**\nDefine two pointers `i1` and `i2` for `word1` and `word2` respectively. Pick word from `word1` iff `word1[i1:] > word2[i2]`.\n\n**Implementation**\n```\nclass Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n ans = []\n i1 = i2 = 0\n while i1 < len(word1) and i2 < le... | 6 | The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.).
The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an inte... | Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to co... |
using two pointers easy-ethiopian nerd | largest-merge-of-two-strings | 0 | 1 | # Intuition\nusnig two pointers\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:o(n*m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:i didnt calculate it\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass S... | 0 | You are given two strings `word1` and `word2`. You want to construct a string `merge` in the following way: while either `word1` or `word2` are non-empty, choose **one** of the following options:
* If `word1` is non-empty, append the **first** character in `word1` to `merge` and delete it from `word1`.
* For e... | null |
using two pointers easy-ethiopian nerd | largest-merge-of-two-strings | 0 | 1 | # Intuition\nusnig two pointers\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:o(n*m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:i didnt calculate it\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass S... | 0 | The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.).
The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an inte... | Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to co... |
simple greedy solution | largest-merge-of-two-strings | 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)$$ -->o(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$... | 0 | You are given two strings `word1` and `word2`. You want to construct a string `merge` in the following way: while either `word1` or `word2` are non-empty, choose **one** of the following options:
* If `word1` is non-empty, append the **first** character in `word1` to `merge` and delete it from `word1`.
* For e... | null |
simple greedy solution | largest-merge-of-two-strings | 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)$$ -->o(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$... | 0 | The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.).
The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an inte... | Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to co... |
Python3 | Two Pointers | Fast | largest-merge-of-two-strings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> Using two pointers, we can compare the characters.\n\n# Approach\n<!-- Describe your approach to solving the problem. --> Compare each character and append accordingly. When two characters are the same, we need to slice and compare the who... | 0 | You are given two strings `word1` and `word2`. You want to construct a string `merge` in the following way: while either `word1` or `word2` are non-empty, choose **one** of the following options:
* If `word1` is non-empty, append the **first** character in `word1` to `merge` and delete it from `word1`.
* For e... | null |
Python3 | Two Pointers | Fast | largest-merge-of-two-strings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> Using two pointers, we can compare the characters.\n\n# Approach\n<!-- Describe your approach to solving the problem. --> Compare each character and append accordingly. When two characters are the same, we need to slice and compare the who... | 0 | The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.).
The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an inte... | Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to co... |
Python3 easy solution | largest-merge-of-two-strings | 0 | 1 | # Code\n```\nclass Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n res = []\n while word1 or word2:\n if word1 >= word2:\n res.append(word1[0])\n word1 = word1[1:]\n else:\n res.append(word2[0])\n wor... | 0 | You are given two strings `word1` and `word2`. You want to construct a string `merge` in the following way: while either `word1` or `word2` are non-empty, choose **one** of the following options:
* If `word1` is non-empty, append the **first** character in `word1` to `merge` and delete it from `word1`.
* For e... | null |
Python3 easy solution | largest-merge-of-two-strings | 0 | 1 | # Code\n```\nclass Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n res = []\n while word1 or word2:\n if word1 >= word2:\n res.append(word1[0])\n word1 = word1[1:]\n else:\n res.append(word2[0])\n wor... | 0 | The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.).
The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an inte... | Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to co... |
[Python3] divide in half | closest-subsequence-sum | 0 | 1 | **Algo**\nDivide `nums` in half. Collect subsequence subs of the two halves respectively and search for a combined sum that is closest to given `target`. \n\n**Implementation**\n```\nclass Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n \n def fn(nums):\n ans = {... | 31 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
[Python3] divide in half | closest-subsequence-sum | 0 | 1 | **Algo**\nDivide `nums` in half. Collect subsequence subs of the two halves respectively and search for a combined sum that is closest to given `target`. \n\n**Implementation**\n```\nclass Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n \n def fn(nums):\n ans = {... | 31 | You are given a very large integer `n`, represented as a string, and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number.
You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal represen... | The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary s... |
Python | Meet In Middle | Simple Solution | closest-subsequence-sum | 0 | 1 | \n# Code\n```\nclass Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n mid = len(nums) // 2\n subSum1 = self.__getSubsequences(nums[:mid], 0, 0)\n subSum2 = self.__getSubsequences(nums[mid:], 0, 0)\n subSum2.sort()\n ans = sys.maxsize\n for ss in s... | 0 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
Python | Meet In Middle | Simple Solution | closest-subsequence-sum | 0 | 1 | \n# Code\n```\nclass Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n mid = len(nums) // 2\n subSum1 = self.__getSubsequences(nums[:mid], 0, 0)\n subSum2 = self.__getSubsequences(nums[mid:], 0, 0)\n subSum2.sort()\n ans = sys.maxsize\n for ss in s... | 0 | You are given a very large integer `n`, represented as a string, and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number.
You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal represen... | The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary s... |
python binary search o(2**(n/2) +2**(n/2) ) | closest-subsequence-sum | 0 | 1 | \n\n# Code\n```\nimport bisect\nclass Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n a,b = [],[]\n for i in range(len(nums)//2):\n a.append(nums[i])\n for i in range(len(nums)//2,len(nums)):\n b.append(nums[i])\n\n s1,s2 = [0],[0]\n ... | 0 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
python binary search o(2**(n/2) +2**(n/2) ) | closest-subsequence-sum | 0 | 1 | \n\n# Code\n```\nimport bisect\nclass Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n a,b = [],[]\n for i in range(len(nums)//2):\n a.append(nums[i])\n for i in range(len(nums)//2,len(nums)):\n b.append(nums[i])\n\n s1,s2 = [0],[0]\n ... | 0 | You are given a very large integer `n`, represented as a string, and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number.
You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal represen... | The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary s... |
Python Soln (Meet in the Middle | combinations) + comments ! | closest-subsequence-sum | 0 | 1 | #### Intuition\nAs all combinations will take too much space so divide the problem in halves & solve inorder to reduce space usage at a time\n\n#### Code\n```\ndef findAllSums(nums):\n res = {0, sum(nums)}\n\n for i in range(1, len(nums)):\n res.update({sum(sub) for sub in combinations(nums, i)})\n \n ... | 0 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
Python Soln (Meet in the Middle | combinations) + comments ! | closest-subsequence-sum | 0 | 1 | #### Intuition\nAs all combinations will take too much space so divide the problem in halves & solve inorder to reduce space usage at a time\n\n#### Code\n```\ndef findAllSums(nums):\n res = {0, sum(nums)}\n\n for i in range(1, len(nums)):\n res.update({sum(sub) for sub in combinations(nums, i)})\n \n ... | 0 | You are given a very large integer `n`, represented as a string, and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number.
You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal represen... | The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary s... |
Pandas vs SQL | Elegant & Short | All 30 Days of Pandas solutions ✅ | recyclable-and-low-fat-products | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```python []\ndef find_products(products: pd.DataFrame) -> pd.DataFrame:\n return products[\n (products[\'low_fats\'] == \'Y\') & \\\n (products[\'recyclable\'] == \'Y\')\n ][[\'product_id\']]\n\n```\n```SQL []\nSELEC... | 8 | Alice and Bob take turns playing a game with **Alice starting first**.
In this game, there are `n` piles of stones. On each player's turn, the player should remove any **positive** number of stones from a non-empty pile **of his or her choice**. The first player who cannot make a move loses, and the other player wins.... | null |
Eazy to understand beat 93% 🚀 | minimum-changes-to-make-alternating-binary-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 a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Eazy to understand beat 93% 🚀 | minimum-changes-to-make-alternating-binary-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 identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
Python | 51ms Faster than 92% | Soln without '%' or 'sum' | minimum-changes-to-make-alternating-binary-string | 0 | 1 | From an observation we can find that ```s = "0100"``` can have only two solutions which are ``` 0101``` and ```1010```.\n\nIf we find the number of operations to change ```s``` to first solution ```0101```, we can find the number of operations required to change ```s``` to second solution ```1010``` with simple maths.\... | 15 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Python | 51ms Faster than 92% | Soln without '%' or 'sum' | minimum-changes-to-make-alternating-binary-string | 0 | 1 | From an observation we can find that ```s = "0100"``` can have only two solutions which are ``` 0101``` and ```1010```.\n\nIf we find the number of operations to change ```s``` to first solution ```0101```, we can find the number of operations required to change ```s``` to second solution ```1010``` with simple maths.\... | 15 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
Python3 solution | O(n) | Explained | minimum-changes-to-make-alternating-binary-string | 0 | 1 | \'\'\'\nSimple idea:\nIn this problem there are 2 possible valid binary strings. Let\'s take an example:\ns = "010011" the answer is : either "010101" or "101010", but you wanna pick the one that is easier to transform.\nIn order to that you have to iterate through the string and count 2 times how many changes you hav... | 14 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Python3 solution | O(n) | Explained | minimum-changes-to-make-alternating-binary-string | 0 | 1 | \'\'\'\nSimple idea:\nIn this problem there are 2 possible valid binary strings. Let\'s take an example:\ns = "010011" the answer is : either "010101" or "101010", but you wanna pick the one that is easier to transform.\nIn order to that you have to iterate through the string and count 2 times how many changes you hav... | 14 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
Python Elegant & Short | Minimum of two | minimum-changes-to-make-alternating-binary-string | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def minOperations(self, s: str) -> int:\n return min(\n sum(int(bit) == i & 1 for i, bit in enumerate(s)),\n sum(int(bit) != i & 1 for i, bit in enumerate(s)),\n )\n```\n | 2 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Python Elegant & Short | Minimum of two | minimum-changes-to-make-alternating-binary-string | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def minOperations(self, s: str) -> int:\n return min(\n sum(int(bit) == i & 1 for i, bit in enumerate(s)),\n sum(int(bit) != i & 1 for i, bit in enumerate(s)),\n )\n```\n | 2 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
Python easy solution | minimum-changes-to-make-alternating-binary-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n2 cases by index:\n- \'01010101...\': (0 - even index, 1 - odd index)\n- \'10101010...\': (1 - even index, 0 - odd index)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Case1: Count number of (0 - even index, 1 - ... | 1 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Python easy solution | minimum-changes-to-make-alternating-binary-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n2 cases by index:\n- \'01010101...\': (0 - even index, 1 - odd index)\n- \'10101010...\': (1 - even index, 0 - odd index)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Case1: Count number of (0 - even index, 1 - ... | 1 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
Python with explanation | minimum-changes-to-make-alternating-binary-string | 0 | 1 | ```\n# The final string should be either 010101.. or 101010... (depending on the length of string s)\n# Check the number of differences between given string s and the two final strings. \n# Return the one with minimum differences \n\n\tdef minOperations(self, s: str) -> int:\n\t\tstarting_with_01 = \'01\'\n\t\tstarting... | 5 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Python with explanation | minimum-changes-to-make-alternating-binary-string | 0 | 1 | ```\n# The final string should be either 010101.. or 101010... (depending on the length of string s)\n# Check the number of differences between given string s and the two final strings. \n# Return the one with minimum differences \n\n\tdef minOperations(self, s: str) -> int:\n\t\tstarting_with_01 = \'01\'\n\t\tstarting... | 5 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
5-Lines Python Solution || Faster than 90% || Memory Less than 70% | minimum-changes-to-make-alternating-binary-string | 0 | 1 | ```\n\tdef minOperations(self, s: str) -> int:\n ref0 = \'01\'*(len(s)//2) + \'0\'*(len(s)%2)\n ref1 = \'10\'*(len(s)//2) + \'1\'*(len(s)%2)\n diff0 = sum([1 for i in range(len(s)) if s[i]!=ref0[i]])\n diff1 = sum([1 for i in range(len(s)) if s[i]!=ref1[i]])\n return min(diff0, diff1)... | 2 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
5-Lines Python Solution || Faster than 90% || Memory Less than 70% | minimum-changes-to-make-alternating-binary-string | 0 | 1 | ```\n\tdef minOperations(self, s: str) -> int:\n ref0 = \'01\'*(len(s)//2) + \'0\'*(len(s)%2)\n ref1 = \'10\'*(len(s)//2) + \'1\'*(len(s)%2)\n diff0 = sum([1 for i in range(len(s)) if s[i]!=ref0[i]])\n diff1 = sum([1 for i in range(len(s)) if s[i]!=ref1[i]])\n return min(diff0, diff1)... | 2 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
One line solution with using itertools.cycle and zip | minimum-changes-to-make-alternating-binary-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)$$ --... | 0 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
One line solution with using itertools.cycle and zip | minimum-changes-to-make-alternating-binary-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)$$ --... | 0 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
Beats 88.01% of users with Python3 | minimum-changes-to-make-alternating-binary-string | 0 | 1 | # Code\n```\nclass Solution:\n\n def minOperations(self, s: str) -> int:\n # 44ms\n # Beats 88.01% of users with Python3\n ptr = True\n op = {True: "1", False: "0"}\n cnta = cntb = 0\n for i in range(len(s)):\n if s[i] != op[ptr]:\n cnta += 1\n ... | 0 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Beats 88.01% of users with Python3 | minimum-changes-to-make-alternating-binary-string | 0 | 1 | # Code\n```\nclass Solution:\n\n def minOperations(self, s: str) -> int:\n # 44ms\n # Beats 88.01% of users with Python3\n ptr = True\n op = {True: "1", False: "0"}\n cnta = cntb = 0\n for i in range(len(s)):\n if s[i] != op[ptr]:\n cnta += 1\n ... | 0 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
Easy to understand - Python | minimum-changes-to-make-alternating-binary-string | 0 | 1 | # Code\n```\nclass Solution:\n def minOperations(self, s: str) -> int:\n l = len(s)\n a, b = \'01\'*math.ceil(l/2), \'10\'*math.ceil(l/2)\n c, d = 0, 0\n \n if l%2:\n a, b = a[:l], b[:l]\n \n for x, y in zip(s, a):\n if x != y:\n c +=1\n \n for i, j in zip(s, b):\n if i... | 0 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Easy to understand - Python | minimum-changes-to-make-alternating-binary-string | 0 | 1 | # Code\n```\nclass Solution:\n def minOperations(self, s: str) -> int:\n l = len(s)\n a, b = \'01\'*math.ceil(l/2), \'10\'*math.ceil(l/2)\n c, d = 0, 0\n \n if l%2:\n a, b = a[:l], b[:l]\n \n for x, y in zip(s, a):\n if x != y:\n c +=1\n \n for i, j in zip(s, b):\n if i... | 0 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
Simplest solution ever | minimum-changes-to-make-alternating-binary-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minOperations(self, s: str) -> int:\n count1=0\n count2=0\n for i in range(len(s)):\n if i%2==0:\n if s[i]==\'1\':\n count1 += 1\n if s[i]==\'0\':\n count2 += 1\n ... | 0 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Simplest solution ever | minimum-changes-to-make-alternating-binary-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minOperations(self, s: str) -> int:\n count1=0\n count2=0\n for i in range(len(s)):\n if i%2==0:\n if s[i]==\'1\':\n count1 += 1\n if s[i]==\'0\':\n count2 += 1\n ... | 0 | You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each ... | Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways. |
【Video】Give me 5 minutes- O(n) time, O(1) space - How we think about a solution | count-number-of-homogenous-substrings | 1 | 1 | # Intuition\nUse two pointers to get length of substring\n\n---\n\n# Solution Video\n\nhttps://youtu.be/VcZrmO045Bo\n\n\u25A0 Timeline of the video\n\n`0:04` Let\'s find a solution pattern\n`1:38` A key point to solve Count Number of Homogenous Substrings\n`2:20` Demonstrate how it works with all the same characters\n`... | 118 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
Python one line | count-number-of-homogenous-substrings | 0 | 1 | ```python []\nclass Solution:\n def countHomogenous(self, s: str) -> int:\n return sum(\n x * (x + 1) >> 1\n for _, grp in groupby(s)\n for x in [len(list(grp))]\n ) % (10**9 + 7)\n\n``` | 3 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
✅ One Line Solution | count-number-of-homogenous-substrings | 0 | 1 | # Approach 1\nUsing groupby.\n```sum(1 for _ in grp)``` - more time consuming, less memory usage.\n```len(list(grp))``` - less time but more memory.\n\n# Code 1.1\n```\nclass Solution:\n def countHomogenous(self, s: str) -> int:\n return sum((l:=sum(1 for _ in grp))*(l + 1)//2 for _, grp in groupby(s))%(10**9... | 3 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
Python 95% beating || Easy solution with explanations || Beginner-friendly | count-number-of-homogenous-substrings | 0 | 1 | # Intuition\nThe problem asks to count the number of substrings in a string such that all the characters in them are the same - and it is important to note that such substrings can and will intersect in the input string.\n# Approach\nMy implementation is quite simple - I go through the string and add to the result the ... | 2 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
[Python3] 2 solutions: Two pointer and math using groupby() | count-number-of-homogenous-substrings | 0 | 1 | ```python3 []\nclass Solution:\n def countHomogenous(self, s: str) -> int:\n res, l = 0, 0\n\n for r, c in enumerate(s):\n if c == s[l]:\n res += r - l + 1\n else:\n l = r\n res += 1\n\n return res % (pow(10, 9) + 7)\n```\n######... | 14 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
✅☑[C++/Java/Python/JavaScript] || Easy Solution || EXPLAINED🔥 | count-number-of-homogenous-substrings | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n1. if size of `s` is 0 .so,returning 0.\n2. making a vector `len` of same length as `s` and 0 as initial input for all.\n3. let value of `len[0]` be 1 , and hence sum will be 1 too.\n4. run a for loop in `s` string .\n5. make the... | 2 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
✅ Python3 | One Line Solution | 90ms | Beats 94% ✅ | count-number-of-homogenous-substrings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFor a single section of contiguous matching characters, the number of homogenous substrings we can make is equal to $$\\sum_{i=1}^n i$$, where $$n$$ is the length of the section we are looking at. Simplified, that summation is equal to ... | 1 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
Exaplained code | Java | Python | C++ | JS | Two Pointer Approach | Simple Solution | count-number-of-homogenous-substrings | 1 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```java []\nclass Solution {\n public int countHomogenous(String s) {\n final int MOD = 1000000007;\n int res = 0, ... | 1 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
Python 4 lines using regex | count-number-of-homogenous-substrings | 0 | 1 | ```\nclass Solution:\n def countHomogenous(self, s: str) -> int:\n\n # create list of s segments of consecutive letters\n # ex: splitS = [\'a\', \'bb\', \'ccc\', \'aa\'] for s = \'abbcccaa\'\n pattern = r\'((\\w)\\2*)\'\n splitS = [match.group(1) for match in re.finditer(pattern, s)]\n\n ... | 1 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
C++ Python sum of n(n+1)/2 ||0 ms Beats 100% | count-number-of-homogenous-substrings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne pass to find out all longest homogenous substrings in `s` , and store the lengths in a container `len_homo`.\n\nC code is rare & implemented & runs in 0 ms & beats 100%\n# Approach\n<!-- Describe your approach to solving the problem. ... | 11 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
Simple pattern based intuitive approach!😸 | count-number-of-homogenous-substrings | 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 \nIf there is just one character, the o... | 1 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
Solution with Sliding Window in Python3 / TypeScript | count-number-of-homogenous-substrings | 0 | 1 | # Intuition\n\nHere we have:\n\n- a string `s`\n- our goal is to count number of **homogenous** substrings\n\nA string is **homogenous** if all the characters of the string are **the same**.\n\n```\n# Example\ns = \'aab\'\n\n# How much a-s and b-s could construct a homogenous substring?\n# Only four - \'a\', \'a\', \'a... | 1 | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Inpu... | null |
[Python3] brute-force | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | Algo\nCheck all trios and find minimum degrees. \n\nImplementation\n```\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n graph = [[False]*n for _ in range(n)]\n degree = [0]*n\n \n for u, v in edges: \n graph[u-1][v-1] = graph[v-1][u-1] = Tru... | 7 | You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pa... | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character.... |
[Python3] brute-force | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | Algo\nCheck all trios and find minimum degrees. \n\nImplementation\n```\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n graph = [[False]*n for _ in range(n)]\n degree = [0]*n\n \n for u, v in edges: \n graph[u-1][v-1] = graph[v-1][u-1] = Tru... | 7 | Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. F... | Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and... |
Python || Beats 100% || O(N^2) | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | # Code\n``` python3 []\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n E = defaultdict(set)\n for a,b in edges:\n E[a].add(b)\n E[b].add(a)\n ret = len(edges)+1\n L = {k:len(E[k])-2 for k in E.keys()}\n K = sorted(L.keys(),... | 0 | You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pa... | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character.... |
Python || Beats 100% || O(N^2) | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | # Code\n``` python3 []\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n E = defaultdict(set)\n for a,b in edges:\n E[a].add(b)\n E[b].add(a)\n ret = len(edges)+1\n L = {k:len(E[k])-2 for k in E.keys()}\n K = sorted(L.keys(),... | 0 | Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. F... | Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and... |
O(m^1.5) algorithm to generate triangles (which is better than O(n^3) or O(n * m)) | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | # Lemma\n###### For any node there are *O(sqrt(m))* adjacent nodes with bigger degree.\n##### Proof\n1) If degree <= *sqrt(m)*, it\'s obvious.\n2) If degree > *sqrt(m)* there are *O(m / sqrt(m))* = *O(sqrt(m))* nodes with degree > *sqrt(m)*. So there are *O(sqrt(m))* potential nodes with bigger degree.\n\n# Approach\n1... | 0 | You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pa... | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character.... |
O(m^1.5) algorithm to generate triangles (which is better than O(n^3) or O(n * m)) | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | # Lemma\n###### For any node there are *O(sqrt(m))* adjacent nodes with bigger degree.\n##### Proof\n1) If degree <= *sqrt(m)*, it\'s obvious.\n2) If degree > *sqrt(m)* there are *O(m / sqrt(m))* = *O(sqrt(m))* nodes with degree > *sqrt(m)*. So there are *O(sqrt(m))* potential nodes with bigger degree.\n\n# Approach\n1... | 0 | Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. F... | Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and... |
[Python] Don't repeat same trios | Optimization | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | \n# Code\n```\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n adj = [set() for i in range(n)]\n deg = [0]*n\n for u,v in edges:\n u -=1\n v-=1\n adj[u].add(v)\n adj[v].add(u)\n deg[u]+=1\n deg[... | 0 | You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pa... | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character.... |
[Python] Don't repeat same trios | Optimization | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | \n# Code\n```\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n adj = [set() for i in range(n)]\n deg = [0]*n\n for u,v in edges:\n u -=1\n v-=1\n adj[u].add(v)\n adj[v].add(u)\n deg[u]+=1\n deg[... | 0 | Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. F... | Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and... |
Simple Adjacency Matrix iteration with Explanation | Python | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLooking at this problem, the first thing that we should be able to infer is that we need to build out an adjacency list since we want to first find 3 connected nodes.\nWe need to understand the concept of "degree" which means the number o... | 0 | You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pa... | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character.... |
Simple Adjacency Matrix iteration with Explanation | Python | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLooking at this problem, the first thing that we should be able to infer is that we need to build out an adjacency list since we want to first find 3 connected nodes.\nWe need to understand the concept of "degree" which means the number o... | 0 | Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. F... | Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and... |
Python | easy Solution | faster than 100% | minimum-degree-of-a-connected-trio-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)$$ --... | 0 | You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pa... | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character.... |
Python | easy Solution | faster than 100% | minimum-degree-of-a-connected-trio-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)$$ --... | 0 | Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. F... | Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and... |
Python common sense approach | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | # Intuition\nA trio is present when the two nodes that are connected by an edge share a neighbor. Count the neighbors of each of these three nodes individually and subtract 6 to account for each member of the trio also having the other two as neighbors.\n\nI was astounded that this worked as it probably has exponential... | 0 | You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pa... | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character.... |
Python common sense approach | minimum-degree-of-a-connected-trio-in-a-graph | 0 | 1 | # Intuition\nA trio is present when the two nodes that are connected by an edge share a neighbor. Count the neighbors of each of these three nodes individually and subtract 6 to account for each member of the trio also having the other two as neighbors.\n\nI was astounded that this worked as it probably has exponential... | 0 | Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. F... | Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and... |
Solution with Recursion Beats 93.85% in Runtime | longest-nice-substring | 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)$$ --... | 11 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
[Python3] brute-force & divide and conquer | longest-nice-substring | 0 | 1 | \n```\nclass Solution:\n def longestNiceSubstring(self, s: str) -> str:\n ans = ""\n for i in range(len(s)):\n for ii in range(i+1, len(s)+1):\n if all(s[k].swapcase() in s[i:ii] for k in range(i, ii)): \n ans = max(ans, s[i:ii], key=len)\n return ans... | 79 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
Python3 - From O(N^2) to O(N) | longest-nice-substring | 0 | 1 | This post is inspired by \nhttps://leetcode.com/problems/longest-nice-substring/discuss/1074677/This-is-a-good-problem-but-it\'s-bad-to-use-small-constraint-and-mark-it-as-an-easy-problem\n\nI want to explain to myself how one can optimize step by step from O(N^2) brute force solution to the optimal solution O(N). \n\n... | 41 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
Python 🐍 | Simple Solution | Divide and Conquer ✅ | longest-nice-substring | 0 | 1 | \n\n# Complexity\n- Time complexity: $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\n def longestNiceSubstring(self, s: str) -> str:\n if len(s) < 2:\n retu... | 1 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
Nice | longest-nice-substring | 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)$$ --... | 7 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
python3 brute force solution | longest-nice-substring | 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 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
✅ Elegant Divide and Conquer Approach | longest-nice-substring | 0 | 1 | # Intuition\nWe are using recursion here\n\n# Approach\nWe find the first letter in the string which doesn\'t have complementary and divide string into two substrings - and so on until we find the string without single letters\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\n... | 7 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
[Python 3] Using a decreasing sliding window. | longest-nice-substring | 0 | 1 | The intuition behind my approach is to check validity for substings starting with the longest one and decreasing our window size.\n\nThe difficult part was determining how to write a function that would determine "niceness." The intuition behind the function I wrote is that if we compare the number of unique characters... | 12 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
[Python3] Recursive Divide and Conquer Solution (O(n)) | longest-nice-substring | 0 | 1 | ```\nclass Solution:\n def longestNiceSubstring(self, s: str) -> str:\n def divcon(s):\n\t\t # string with length 1 or less arent considered nice\n if len(s) < 2:\n return ""\n \n pivot = []\n # get every character that is not nice\n for... | 13 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
Python - Simple and Elegant! Multiple Solutions! | longest-nice-substring | 0 | 1 | **Brute Force**:\n```\nclass Solution:\n def longestNiceSubstring(self, s):\n subs = [s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)]\n nice = [sub for sub in subs if set(sub)==set(sub.swapcase())]\n return max(nice, key=len, default="")\n```\n\n**Divide and Conquer ([Credit](https:... | 11 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
Python Stack divide an conquer | longest-nice-substring | 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 | A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _th... | null |
Super Simple Python Solution (check one by one) | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n pointer = 0\n \n groups.reverse()\n \n while pointer <= len(nums):\n if len(groups) == 0:\n return True\n currentGroup = groups[-1]\n ... | 1 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
Super Simple Python Solution (check one by one) | form-array-by-concatenating-subarrays-of-another-array | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n pointer = 0\n \n groups.reverse()\n \n while pointer <= len(nums):\n if len(groups) == 0:\n return True\n currentGroup = groups[-1]\n ... | 1 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
Hideous Python one liner | form-array-by-concatenating-subarrays-of-another-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 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
Hideous Python one liner | form-array-by-concatenating-subarrays-of-another-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 | The **product sum** of two equal-length arrays `a` and `b` is equal to the sum of `a[i] * b[i]` for all `0 <= i < a.length` (**0-indexed**).
* For example, if `a = [1,2,3,4]` and `b = [5,2,3,1]`, the **product sum** would be `1*5 + 2*2 + 3*3 + 4*1 = 22`.
Given two arrays `nums1` and `nums2` of length `n`, return _t... | When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays. |
[Python3🐍] [DP] [Drawing✍️] [Easy to understand ✌️] Dynamic Programming solution.✨🍻 | form-array-by-concatenating-subarrays-of-another-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\nConsider we have these three arrarys:\n- groups, provided by input.\n- nums, also provided by input.\n- dp, we create it, the meaning is: **in the current position `... | 1 | You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith`... | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.