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 solution with clear approach explanation 98.22% beats | maximum-alternating-subsequence-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn the problem statement it was clearly mentioned that we need to take maximum altering sum. so we have to take one max element and then a min element and that too in order.\n\n# Approach\n<!-- Describe your approach to solving the proble... | 3 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any... | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the... |
📌 4 lines || 96% faster || Easy-approach 🐍 | maximum-alternating-subsequence-sum | 0 | 1 | ## IDEA:\n\uD83D\uDC49 Maximize the max_diff.\n\uD83D\uDC49 Minimize the min_diff.\nGiven an alternating sequence (a0, a1... ak), the change in value after appending an element x depends only on whether we have an even or odd number of elements so far:\n\nIf we have even # of elements, we add x; otherwise, we subtract ... | 9 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any... | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the... |
Python Easy memoization | maximum-alternating-subsequence-sum | 0 | 1 | ```\nclass Solution(object):\n def maxAlternatingSum(self, nums):\n dp = {}\n def max_sum(arr,i,add = False):\n if i>=len(arr):\n return 0\n if (i,add) in dp:\n return dp[(i,add)]\n nothing = max_sum(arr,i+1, add)\n if not add:\... | 1 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any... | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the... |
Python 3 | DP, O(N) | Explanation | maximum-alternating-subsequence-sum | 0 | 1 | ### Explanation\n- Only 2 different states: even sum or odd sum\n- Like the `hint` section, you can keep 2 variables and track the mamimum along the way\n- See below for more explanation\n### Implementation\n```\nclass Solution:\n def maxAlternatingSum(self, nums: List[int]) -> int:\n # even: max alternating ... | 4 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any... | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the... |
[Python3] priority queues | design-movie-rental-system | 0 | 1 | \n```\nclass MovieRentingSystem:\n\n def __init__(self, n: int, entries: List[List[int]]):\n self.avail = {}\n self.price = {}\n self.movies = defaultdict(list)\n for s, m, p in entries: \n heappush(self.movies[m], (p, s))\n self.avail[s, m] = True # unrented \n ... | 9 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
[Python] beat 100% Time 100% Space with a Top5HeapSet | design-movie-rental-system | 0 | 1 | # Code\n```\nclass Top5HeapSet:\n def __init__(self):\n self._top5 = []\n self._heap = []\n self._to_remove = set()\n\n def top5(self):\n return self._top5\n\n def add(self, val):\n if val in self._to_remove:\n self._to_remove.remove(val)\n else:\n ... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
Python solution using dictionaries and set | design-movie-rental-system | 0 | 1 | The way it handles availability could be improved. It is still faster than other Python solutions. Possible reason is the version change in Python. \n\n# Code\n```\nclass MovieRentingSystem:\n\n def __init__(self, n: int, entries: List[List[int]]):\n\n movies = defaultdict(list)\n \n for shop, m... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
SortedDict python | design-movie-rental-system | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
python | design-movie-rental-system | 0 | 1 | # Code\n```\nfrom sortedcontainers import SortedList\nclass MovieRentingSystem:\n\n def __init__(self, n: int, entries: List[List[int]]):\n self.movies = defaultdict(SortedList)\n self.shop = {}\n \n for s, m, p in entries:\n self.shop[(s, m)] = p\n self.movies[m].ad... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
Python Easy Solution Using SortedList | Faster than 99% | | design-movie-rental-system | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
Python (BEATS 100%) Solution with heaps and memoization | design-movie-rental-system | 0 | 1 | Previous `search()` and `report()` calls are stored and returned if no updates have been made yet.\n\n# Code\n```\nfrom heapq import heappush\nclass MovieRentingSystem:\n\n def __init__(self, n: int, entries: List[List[int]]):\n self.movies = {}\n self.prices = {}\n self.rented = set()\n ... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
Python sortedlist solution | design-movie-rental-system | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Used sorted sets to handle rented and unrented movies\n- Also need map of {shop: {movie: price}} to keep track of movie prices\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
Python (Simple Maths) | design-movie-rental-system | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
【Video】Give me 5 minutes - How we think about a solution | maximum-product-difference-between-two-pairs | 1 | 1 | # Intuition\r\nUse the two biggest numbers and the two smallest numbers\r\n\r\n---\r\n\r\n# Solution Video\r\n\r\nhttps://youtu.be/DMzedO_tGr8\r\n\r\n\u25A0 Timeline of the video\r\n\r\n`0:05` Explain solution formula\r\n`0:47` Talk about the first smallest and the second smallest\r\n`3:32` Talk about the first biggest... | 36 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
1-line vs 2 priority_queues vs loop||11 ms Beats 99.06% | maximum-product-difference-between-two-pairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse sort 1-line by Python\nC++ sort.\nOther approaches are\n- Heap solution\n- Loop with conditional clause\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[https://youtu.be/I2VRYiBjK1k?si=UkDt91Fhu3wAh1K2](https://y... | 8 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
🔥 Beats 100% | 2 Approaches | Easiest code with explaination 🚀😎 | maximum-product-difference-between-two-pairs | 1 | 1 | # Intuition\r\nThe goal is to maximize the product difference between two pairs. To achieve this, we want to select the two largest numbers for the first pair and the two smallest numbers for the second pair. By sorting the array and choosing the extremes, we can maximize the product difference.\r\n<!-- Describe your f... | 4 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
Leetcode daily problems 🔥 | Easy Explanation | C++✔ | JAVA✔ | PYTHON✔ | C ✔| | maximum-product-difference-between-two-pairs | 1 | 1 | # ***Please upvote , if you find it a little helpful*\uD83D\uDE22**\n\n---\n\n\n# Approach 1 : Using sorting\n# Intuition\nThe goal is to find the maximum product difference between two pairs of distinct indices.\n\n# Approach\nThe algorithm utilizes sorting to find the maximum product difference between two pairs of d... | 4 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
Python3 Solution | maximum-product-difference-between-two-pairs | 0 | 1 | \n```\nclass Solution:\n def maxProductDifference(self, nums: List[int]) -> int:\n nums.sort()\n return (nums[-1]*nums[-2])-(nums[0]*nums[1])\n``` | 3 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥 | maximum-product-difference-between-two-pairs | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n*(Also explained in the code)*\n\n#### ***Approach 1(with Sort)***\n1. sorts the input array `nums` in ascending order.\n1. Computes the difference between the product of the last two elements and the product of the first two elements in the sorted array.\n 1. Retu... | 10 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
✅ One Line Solution | maximum-product-difference-between-two-pairs | 0 | 1 | # Code #1 - Fast\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def maxProductDifference(self, A: List[int]) -> int:\n return prod(nlargest(2,A)) - prod(nsmallest(2,A))\n```\n\n# Code #2 - Slow\nTime complexity: $$O(n*log(n))$$. Space complexity: $$O(n)$$.\n```\nclass Solution... | 4 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
Simple and Easy Code to understand ||Beginner Friendly||C++||java||python | maximum-product-difference-between-two-pairs | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n log n), where n is the number of elements in the input array. This is because sorting the array takes O(n log n) time.\n\n- Spa... | 8 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
Beats 99% || [Java/C++/Python3] || Beginner Friendly Solution | maximum-product-difference-between-two-pairs | 1 | 1 | # Intuition\n1. Product difference will be maximum when we will, subtract of two smallest number from the product of two greatest number.\n2. We have to find the greatest two number and smallest two number.\n\n# Approach\n1. **Initialization:**\n - Set `min1` to the first element in the array (nums[0]).\n - Set ... | 1 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
simple and easy to understand solution using java and python | maximum-product-difference-between-two-pairs | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves finding the maximum product difference between pairs of elements in an array. To maximize the product difference, we should select the largest and second-largest elements and the smallest and second-smallest elements.... | 1 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
O(n) solution | 1 pass ✅🏁 | maximum-product-difference-between-two-pairs | 0 | 1 | # Intuition\r\nWe can get the $$Biggest$$ $$Difference$$ when we find the difference b/w the products of the highest two integers and the lowest two integers.\r\n\r\n**Why?**\r\nProduct of the lowest two integers gives the lowest possible product\r\nAnd the product between the two highest integers gives the highest pos... | 1 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
Python 3 || 12 lines, each layer as 1D array || T/M: 98% / 96% | cyclically-rotating-a-grid | 0 | 1 | ```\r\nclass Solution:\r\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\r\n \r\n m, n = len(grid), len(grid[0])\r\n MN = min(m, n)//2\r\n \r\n for i in range(MN):\r\n\r\n XO, X1, YO, Y1 = i, m-i-1, i, n-i-1\r\n rot = k%(2*(X1+Y1-XO-YO)) \r\... | 3 | You are given an `m x n` integer matrix `grid`, where `m` and `n` are both **even** integers, and an integer `k`.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matr... | null |
Python 3 || 12 lines, each layer as 1D array || T/M: 98% / 96% | cyclically-rotating-a-grid | 0 | 1 | ```\r\nclass Solution:\r\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\r\n \r\n m, n = len(grid), len(grid[0])\r\n MN = min(m, n)//2\r\n \r\n for i in range(MN):\r\n\r\n XO, X1, YO, Y1 = i, m-i-1, i, n-i-1\r\n rot = k%(2*(X1+Y1-XO-YO)) \r\... | 3 | You are given an `m x n` integer matrix `grid`, where `m` and `n` are both **even** integers, and an integer `k`.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matr... | null |
[Python3] brute-force | cyclically-rotating-a-grid | 0 | 1 | \n```\nclass Solution:\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n m, n = len(grid), len(grid[0]) # dimensions \n \n for r in range(min(m, n)//2): \n i = j = r\n vals = []\n for jj in range(j, n-j-1): vals.append(grid[i][jj])\n... | 26 | You are given an `m x n` integer matrix `grid`, where `m` and `n` are both **even** integers, and an integer `k`.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matr... | null |
📌 Simple-Approach || Well-explained || 95% faster 🐍 | cyclically-rotating-a-grid | 0 | 1 | ## IDEA: \n\uD83D\uDC49 keep the boundary matrix in a list\n\uD83D\uDC49 Then rotate by len % k\n\uD83D\uDC49 again store in the matrix\n\'\'\'\n\n\tclass Solution:\n def rotateGrid(self, mat: List[List[int]], k: int) -> List[List[int]]:\n \n top = 0\n bottom = len(mat)-1\n left = 0\n ... | 7 | You are given an `m x n` integer matrix `grid`, where `m` and `n` are both **even** integers, and an integer `k`.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matr... | null |
Rotate in-place. Space O(1). Time O(n). | cyclically-rotating-a-grid | 0 | 1 | ```\r\nclass Solution:\r\n def translate(self, i, a, bx, by):\r\n dx, dy = bx-a-1, by-a-1\r\n if i <= dy:\r\n return (a, i+a)\r\n i -= dy\r\n if i <= dx:\r\n return (i+a, by-1)\r\n i -= dx\r\n if i <= dy:\r\n return (bx-1, by-i-1)\r\n ... | 0 | You are given an `m x n` integer matrix `grid`, where `m` and `n` are both **even** integers, and an integer `k`.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matr... | null |
[Python3] - Layerwise Modulo Rotation - O(m+n) Space - O(m*n) Time | cyclically-rotating-a-grid | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nFirst thing is to understand that its way better to compute the updated position of an element in O(1) other than simulating every of the k shifts.\r\n\r\nWe then need a function that computes the rx and cx for every position in one l... | 0 | You are given an `m x n` integer matrix `grid`, where `m` and `n` are both **even** integers, and an integer `k`.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matr... | null |
[Python3] Solving like Spiral Matrix | cyclically-rotating-a-grid | 0 | 1 | # Code\r\n```\r\nclass Solution:\r\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\r\n m = len(grid)\r\n n = len(grid[0])\r\n rDir = [0, 1, 0, -1]\r\n cDir = [1, 0, -1, 0]\r\n\r\n dir = 0\r\n l = m*n\r\n\r\n r = 0\r\n c = 0\r\n\r\n ... | 0 | You are given an `m x n` integer matrix `grid`, where `m` and `n` are both **even** integers, and an integer `k`.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matr... | null |
[Spaghetti Code] what did i write..... | cyclically-rotating-a-grid | 0 | 1 | # Intuition\r\nI know this hurt your eyes.. buy i really want to post it out......\r\n**DO NOT LEARN FROM THIS !@#!**\r\n\r\n\r\n# Readability\r\nNone, zero, written by idiot\r\n\r\n# Approach\r\ngroup by layer --> reshape layer in clockwise manner --> add offset and transform back to traditional array\r\n\r\n# Complex... | 0 | You are given an `m x n` integer matrix `grid`, where `m` and `n` are both **even** integers, and an integer `k`.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matr... | null |
Python Solution | Detailed Explenation | number-of-wonderful-substrings | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n- We want to iterate through all substrings and check if each one has at most 1 oddly occurring letter\r\n- Tracking odd/even counts directly for all letters would be complicated\r\n- Instead, we can encode the state as a bitmask to t... | 0 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
[Python 3] Bitmask - O(n), O(1) | number-of-wonderful-substrings | 0 | 1 | \n# Code\n```\nclass Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n seen = defaultdict(int)\n seen[0] += 1\n ans = 0\n mask = 0\n for c in word:\n mask ^= (1 << (ord(c) - ord(\'a\')))\n ans += seen[mask]\n for i in range(ord(\'j\') -... | 1 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
[Python3] freq table w. mask | number-of-wonderful-substrings | 0 | 1 | \n```\nclass Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n ans = mask = 0\n freq = defaultdict(int, {0: 1})\n for ch in word: \n mask ^= 1 << ord(ch)-97\n ans += freq[mask]\n for i in range(10): ans += freq[mask ^ 1 << i]\n freq[mask] ... | 11 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Python O(n) solution with comments, Prefix sum, bit mask | number-of-wonderful-substrings | 0 | 1 | explaination for this `res+=dp[curr ^(1<<i)]`.\nIntuition :\nThis was similar to solving the problem of finding the subarray of sum k. This can be solved using prefix sum concept . For example given an array a= [ 2, 3 ,4 ,5 ,10] and k=9, we can calculate running sum and store Its prefix sum array as dp=[2,5,9,14,24].... | 6 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Easiest Python Solution using bit manipulation | number-of-wonderful-substrings | 0 | 1 | # Code\r\n```\r\nclass Solution:\r\n def wonderfulSubstrings(self, word: str) -> int:\r\n ans=mask=0 #consider mask be 0\r\n freq=defaultdict(int,{0:1}) #for counting freq if that mask may already appear or not\r\n\r\n for i in word:\r\n mask^=1<<ord(i)-97 # mask it \r\n ... | 0 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Python Solution | number-of-wonderful-substrings | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity ... | 0 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Counting Wonderful Substrings: An Efficient Algorithm Using Bit Manipulation | number-of-wonderful-substrings | 0 | 1 | # Intuition\r\nThe problem is about counting the number of "wonderful" substrings in a given word. A "wonderful" substring is one in which at most one character occurs an odd number of times. The first thought is to check every possible substring, but that would be inefficient. A better way might be to use bitwise mani... | 0 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Python Solution using bit-masking and find pair which have xor equal to target in O(n*10) and O(1) | number-of-wonderful-substrings | 0 | 1 | # Code\n```\nclass Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n s=ans=0\n d={0:1}\n for val in word:\n s^=(1<<(ord(val)-97))\n for item in [0,1,2,4,8,16,32,64,128,256,512]:\n if(item^s in d):\n ans+=d[item^s]\n ... | 0 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Bitwise Masking for Efficiently Counting Wonderful Substring (91% beats) | number-of-wonderful-substrings | 0 | 1 | # Intuition\r\nGiven a word, our objective is to find out how many of its substrings are "wonderful". A substring is considered "wonderful" if at most one of its characters appears an odd number of times. The direct approach would be to generate all substrings and then check the frequency of each character in every sub... | 0 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Python | Bitmask | O(10n) | number-of-wonderful-substrings | 0 | 1 | # Code\n```\nfrom collections import defaultdict\nclass Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n d = defaultdict(int)\n mask = 0\n d[mask] = 1\n res = 0\n for c in word:\n mask ^= 1 << (ord(c)-ord(\'a\'))\n res += d[mask]\n for... | 0 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Recursive Python Solution | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | # Intuition\r\nSince we need to build certain rooms before others, it is clear we need to use topological sorting to find a valid combination.\r\n\r\nBut how do we get all combinations that are valid? Let\'s think in simpler cases:\r\n1. If the tree consists of one path, there is only one valid combination (See the fir... | 1 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
Recursive Python Solution | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | # Intuition\r\nSince we need to build certain rooms before others, it is clear we need to use topological sorting to find a valid combination.\r\n\r\nBut how do we get all combinations that are valid? Let\'s think in simpler cases:\r\n1. If the tree consists of one path, there is only one valid combination (See the fir... | 1 | We are given a list `nums` of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from l... | Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplie... |
Explanation of Another Users Solution | Comments, Explanation, Example | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nAll credit for intution goes to user solution at https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/solutions/1299545/python3-post-order-dfs/\r\n\r\nI include comments, explanation and example walkthrough for com... | 1 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
Explanation of Another Users Solution | Comments, Explanation, Example | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nAll credit for intution goes to user solution at https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/solutions/1299545/python3-post-order-dfs/\r\n\r\nI include comments, explanation and example walkthrough for com... | 1 | We are given a list `nums` of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from l... | Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplie... |
[Python3] post-order dfs | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | \n```\nclass Solution:\n def waysToBuildRooms(self, prevRoom: List[int]) -> int:\n tree = defaultdict(list)\n for i, x in enumerate(prevRoom): tree[x].append(i)\n \n def fn(n): \n """Return number of nodes and ways to build sub-tree."""\n if not tree[n]: return 1, 1 ... | 10 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
[Python3] post-order dfs | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | \n```\nclass Solution:\n def waysToBuildRooms(self, prevRoom: List[int]) -> int:\n tree = defaultdict(list)\n for i, x in enumerate(prevRoom): tree[x].append(i)\n \n def fn(n): \n """Return number of nodes and ways to build sub-tree."""\n if not tree[n]: return 1, 1 ... | 10 | We are given a list `nums` of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from l... | Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplie... |
Python 3 solution | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity ... | 0 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
Python 3 solution | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity ... | 0 | We are given a list `nums` of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from l... | Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplie... |
Python (Simple Maths) | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity ... | 0 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
Python (Simple Maths) | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity ... | 0 | We are given a list `nums` of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from l... | Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplie... |
[Python] Beats [94.74%, 40.35%] with easy simple structure | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | ```\nimport math\nclass Solution:\n def waysToBuildRooms(self, p: List[int]) -> int:\n def aux(l):\n sum_l = sum(l)\n l.sort(reverse=True)\n i = l[0]\n a = 1\n for j in range(1, len(l)):\n for k in range(l[j]):\n a *= (i+... | 1 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
[Python] Beats [94.74%, 40.35%] with easy simple structure | count-ways-to-build-rooms-in-an-ant-colony | 0 | 1 | ```\nimport math\nclass Solution:\n def waysToBuildRooms(self, p: List[int]) -> int:\n def aux(l):\n sum_l = sum(l)\n l.sort(reverse=True)\n i = l[0]\n a = 1\n for j in range(1, len(l)):\n for k in range(l[j]):\n a *= (i+... | 1 | We are given a list `nums` of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from l... | Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplie... |
Python3 and C++ Solutions | build-array-from-permutation | 0 | 1 | # Solution in C++\n```\nclass Solution {\npublic:\n vector<int> buildArray(vector<int>& nums) {\n vector<int> answer;\n for (int i = 0; i < nums.size(); i++) {\n answer.push_back(nums[nums[i]]);\n }\n return answer;\n }\n};\n```\n# Solution in Python3\n```\nclass Solution:\n... | 2 | Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it.
A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**).
**Example 1:**
*... | Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern. |
Simple python solution | build-array-from-permutation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it.
A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**).
**Example 1:**
*... | Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern. |
Simple Brute Force Method | build-array-from-permutation | 0 | 1 | # Code\n```\nclass Solution:\n def buildArray(self, nums: List[int]) -> List[int]:\n ans = []\n for i in range(len(nums)):\n ans.append(nums[nums[i]])\n return ans\n``` | 1 | Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it.
A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**).
**Example 1:**
*... | Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern. |
beginner friendly in python with memory beats of 100% | build-array-from-permutation | 0 | 1 | \nclass Solution:\n def buildArray(self, nums: List[int]) -> List[int]:\n lst=[]\n for i in range(len(nums)):\n lst.append(nums[nums[i]])\n return lst\n``` | 1 | Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it.
A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**).
**Example 1:**
*... | Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern. |
Python one line simple solution | build-array-from-permutation | 0 | 1 | **Python :**\n\n```\ndef buildArray(self, nums: List[int]) -> List[int]:\n\treturn [nums[i] for i in nums]\n```\n\n**Like it ? please upvote !** | 48 | Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it.
A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**).
**Example 1:**
*... | Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern. |
【Video】Give me 10 minutes - O(n) solution - How we think about a solution | eliminate-maximum-number-of-monsters | 1 | 1 | # Intuition\nWe can calculate number of turns to arrive at the city\n\n# Approach\n\n---\n\n# Solution Video\n\nhttps://youtu.be/2tUBAJEn-S8\n\n\u25A0 Timeline of the video\n\n`0:04` Heap solution I came up with at first\n`2:38` Two key points with O(n) solution for Eliminate Maximum Number of Monsters\n`2:59` Explain ... | 49 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
Python3 Solution | eliminate-maximum-number-of-monsters | 0 | 1 | \n```\nclass Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n n=len(dist)\n time=[]\n for i in range(n):\n time.append((dist[i]/speed[i]))\n time.sort()\n for i in range(n):\n if i>=time[i]:\n i-=1\n ... | 3 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥 | eliminate-maximum-number-of-monsters | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Sort by arrival time)***\n1. **Input Parameters:** The function `eliminateMaximum` takes two input vectors, `dist` and `speed`, representing the distance and speed of each character.\n\n1. **Arrival Time Calcul... | 2 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
O(n) solve | count the monster | dp | prefix Sum | eliminate-maximum-number-of-monsters | 0 | 1 | \n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n \n #deducing the time to reach in the city for every monster\n for i in range(len(dist)): dist[i]/=speed[i] \n\n\n ... | 2 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
🔥BEATS 100% | ✅[PY / Java / C++ / C / C# / JS / Swift / Ruby] | eliminate-maximum-number-of-monsters | 1 | 1 | \n```python []\nclass Solution:\n def eliminateMaximum(self, dist, speed):\n n = len(dist)\n time = [float(d) / s for d, s in zip(dist, speed)]\n time.sort()\n \n curr = 0\n for i in range(n):\n if time[i] <= i:\n break\n curr += 1\n ... | 2 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
C++ O(n) Prefix sum||52ms beats 100%||w pyplot fig | eliminate-maximum-number-of-monsters | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust consider the arrival times of monsters.\nIn fact just consider how many monsters in the time iterval (t-1, t] will arrive.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Chinese spoken! Please turn English su... | 24 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
Python 3 | One line | Beats 99% | eliminate-maximum-number-of-monsters | 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 playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
Python one-liner | eliminate-maximum-number-of-monsters | 0 | 1 | It\'s just a simple Python one-liner, \'cause I haven\'t seen one.\n```\nclass Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n return next((i for i, t in enumerate(sorted(d / s for d, s in zip(dist, speed))) if i >= t), len(dist))\n\n``` | 1 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
Space : O(1), Time : O(nlogn) Daily Challenge 7-Nov-2023, python3 | eliminate-maximum-number-of-monsters | 0 | 1 | \n\n\n# Approach\nCalculate the no.of steps well in advance and sort them. Check the no.of monsters that can be killed before they could approach the city\n\n# Complexity\n- Time complexity: $$O(nlogn)$$\nSor... | 1 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
Beats 99% Python3 | eliminate-maximum-number-of-monsters | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBy calculating arrival times of each monster, and knowing we can always kill first monster at t=0, we can have a go at counting the number of kills before one reaches the city. The first element in the sorted arrival times can never arriv... | 1 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
Easy python solution using greedy and sorting | eliminate-maximum-number-of-monsters | 0 | 1 | # Intuition\nfind the `arrival time` of each monster and find out how many you can eliminate.\n\n# Approach\nsort the `arrival time` and check if arrival > `ith` min, increment `counter` else break.\n\nfinally return `counter`.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```py\... | 1 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
Python3 O(n) FT 99%: Ceil | eliminate-maximum-number-of-monsters | 0 | 1 | # Intuition\n\nMost solutions sort by arrival time in $O(n \\log(n))$ time, and $O(N)$ extra space because a list of arrival times must exist to be sorted.\n\nThe idea is that for each cannon shot, we see if the next monster would arrive before, at, or on that time:\n* before the time: we lose\n* at the same time: we l... | 1 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
✅ Python3 | 666ms Beats 99% | 4 Lines | Easy to Understand ✅ | eliminate-maximum-number-of-monsters | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe best strategy is to kill the monsters in the order that they will arrive. With that in mind it becomes clear that we should sort the monsters by their arrival time, and then check if we have enough time to kill each monster, stoppin... | 1 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
Beats 100% in python. O(n logn) - Time | eliminate-maximum-number-of-monsters | 0 | 1 | \n\n\n\n\n# Intuition and Approach\n- Calculate the time and sort it.\n- The time here is the time the monster will take to reach the city. \n- We sort it because we have to kill the monster which will reach... | 1 | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed... | null |
Easy to understand code ,one liner. | count-good-numbers | 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 digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`).
* For example, `"2582 "` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. Howe... | null |
Using exponentiation squaring | count-good-numbers | 0 | 1 | # Intuition\nI realized that the problem is basically finding the product of 5\\*4\\*5\\*4\\*... where the no. of numbers we are multiplying is n (given).\n\nSo I tried looking for ways to multiply a number repeatedly mod k (=10**9 + 7). \n\n# Approach\nFirst I tried using for loops, but that gave time limit exceeded.\... | 1 | A digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`).
* For example, `"2582 "` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. Howe... | null |
Easy Iterative Binary exponentiation | Python | C++ | Golang | count-good-numbers | 0 | 1 | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(log n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```python []\nimport math\n\nclass Solution:\n MOD = int(1e9+7)\n\n @staticmethod\n def binexp(a, b, MOD):\n ... | 5 | A digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`).
* For example, `"2582 "` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. Howe... | null |
Python, recursion beats 81%, running time 44ms | count-good-numbers | 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- Spilt numbers of odd indexes and even indexes in separate variables.\n- Using binary exponentiation to calculate the `5**even_indexes and 4**odd_indexes`\n- Using Mo... | 4 | A digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`).
* For example, `"2582 "` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. Howe... | null |
[Java/Python 3] Iterative O(logn) code, similar to LC50 Pow(x, n) w/ brief explanation and analysis. | count-good-numbers | 1 | 1 | 1. For each even index, there are 5 options: `0`, `2`, `4`, `6`, `8`;\n2. For each odd index, there are 4 options: `2`, `3`, `5`, `7`;\n3. If `n` is even, the solution is `(4 * 5) ^ (n / 2)`; if odd, `(4 * 5) ^ (n / 2) * 5`.\n\n**Method 1: Bruteforce**\n\nThe input range is as large as `10 ^ 15`, hence the following br... | 21 | A digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`).
* For example, `"2582 "` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. Howe... | null |
Python Solution One Linear || Easy to understand | count-good-numbers | 0 | 1 | ```\nfrom math import ceil,floor\nclass Solution:\n def countGoodNumbers(self, n: int) -> int:\n return (pow(5,ceil(n/2),1000_000_007) * pow(4,floor(n/2),1000_000_007))% 1000_000_007\n``` | 2 | A digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`).
* For example, `"2582 "` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. Howe... | null |
📌 Well-explained || 4 Lines || 97% faster || easily-understandable 🐍 | count-good-numbers | 0 | 1 | ## Idea :\n\uD83D\uDC49 *find number of odd and even places of from given n.*\n\uD83D\uDC49 *each even places can take (0,2,4,6,8) 5 different numbers.*\n\uD83D\uDC49 *each odd places can take (2,3,5,7) 4 different prime numbers.*\n\uD83D\uDC49 *return the total combination of both even and odd places.*\n\n### **pow(a... | 9 | A digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`).
* For example, `"2582 "` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. Howe... | null |
[Python3] Powermod hack, 3 lines | count-good-numbers | 0 | 1 | ---\n- ### the combinatorics part goes like this:\n- there are ceil(n/2) even positions and floor(n/2) odd positions\n- for each even positions the variations are (02,4,6,8). there are five variations for each even position.\n- for each odd position the variations are (2,3,5,7). there are four variations for each odd p... | 5 | A digit string is **good** if the digits **(0-indexed)** at **even** indices are **even** and the digits at **odd** indices are **prime** (`2`, `3`, `5`, or `7`).
* For example, `"2582 "` is good because the digits (`2` and `8`) at even positions are even and the digits (`5` and `2`) at odd positions are prime. Howe... | null |
Python (Simple Binary Search) | longest-common-subpath | 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 | There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting **every pair** of cities.
There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an inte... | One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix. |
[Python3] rolling hash | longest-common-subpath | 0 | 1 | \n```\nclass RabinKarp: \n\n def __init__(self, s): \n """Calculate rolling hash of s"""\n self.m = 1_111_111_111_111_111_111\n self.pow = [1]\n self.roll = [0] # rolling hash \n\n p = 1_000_000_007\n for x in s: \n self.pow.append(self.pow[-1] * p % self.m)\n ... | 0 | There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting **every pair** of cities.
There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an inte... | One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix. |
Easy python solution | count-square-sum-triples | 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)$$ --... | 3 | A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2... | The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map... |
Beats 95.86% || Count square sum triples | count-square-sum-triples | 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)$$ --... | 3 | A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2... | The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map... |
Python simple solution | count-square-sum-triples | 0 | 1 | **Python :**\n\n```\ndef countTriples(self, n: int) -> int:\n\tres = 0\n\n\tfor i in range(1, n):\n\t\tfor j in range(i + 1, n):\n\t\t\ts = math.sqrt(i * i + j * j)\n\t\t\tif int(s) == s and s <= n:\n\t\t\t\tres += 2\n\n\treturn res\n```\n\n**Like it ? please upvote !** | 31 | A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2... | The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map... |
[Python 3] Brute force with optimisation || beats 93% || 145ms | count-square-sum-triples | 0 | 1 | ```python3 []\nclass Solution:\n def countTriples(self, n: int) -> int:\n res, limit = 0, n*n\n for i in range(1, n):\n for j in range(i+1, n):\n k = i*i + j*j\n if k > limit: break\n if sqrt(k) % 1 == 0:\n res += 2\n ... | 4 | A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2... | The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map... |
Easy Solution || PYTHON | count-square-sum-triples | 0 | 1 | ```\n```class Solution:\n def countTriples(self, n: int) -> int:\n count = 0\n sqrt = 0\n for i in range(1,n-1):\n for j in range(i+1, n):\n sqrt = ((i*i) + (j*j)) ** 0.5\n if sqrt % 1 == 0 and sqrt <= n:\n count += 2\n return (c... | 2 | A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2... | The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map... |
Easy Solution Beats 90% | count-square-sum-triples | 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 **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2... | The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map... |
count-square-sum-triples | count-square-sum-triples | 0 | 1 | # Code\n```\nclass Solution:\n def countTriples(self, n: int) -> int:\n l = []\n for i in range(1,n+1):\n l.append(pow(i,2))\n count = 0\n for i in range(len(l)-1,2,-1):\n for j in range(i):\n a = l[i] - l[j]\n if a in l[:i]:\n ... | 0 | A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2... | The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map... |
python simple solution | count-square-sum-triples | 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 **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2... | The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map... |
Python solution || BFS | nearest-exit-from-entrance-in-maze | 0 | 1 | \n# Code\n```\nfrom queue import Queue\n\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n \n q = Queue()\n q.put((entrance[0] , entrance[1] , 0))\n t = 0\n ans =[]\n maze[entrance[0]][entrance[1]] = "+"\n \n while(not q.em... | 1 | You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move o... | null |
Python3 Breadth First Search Solution | nearest-exit-from-entrance-in-maze | 0 | 1 | \n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n m = len(maze)\n n = len(maze[0])\n\n queue = collections.deque()\n queue.append((entrance[0], entrance[1], 0))\... | 0 | You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move o... | null |
Python 3 | Simple Math | Explanation | sum-game | 0 | 1 | ### Explanation\n- Intuition: Starting with the three examples, you will soon realize that this is essentially a Math problem.\n- Our goal is to see if left sum can equal to right sum, that is, `left_sum - right_sum == 0`. \n- To make it easier to understand, we can move digits to one side and `?` mark to the other sid... | 25 | Alice and Bob take turns playing a game, with **Alice** **starting first**.
You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`:
1. Choose an index `i` where `num[i] == '?'`.
2. Replace ... | It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next |
Python 3 || 3 lines, w/ example || T/M: 100% / 8% | sum-game | 0 | 1 | ```\nclass Solution:\n def sumGame(self, num: str) -> bool: # Example: num = "?2936 5??6?"\n\n n = len(num)//2 # n = 10//2 = 5\n num = [9 if ch==\'?\' else 2*int(ch) for ch in num] # num = [_,4,18,6,12, 10,_,_,12,_] <-- double the digits\n ... | 4 | Alice and Bob take turns playing a game, with **Alice** **starting first**.
You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`:
1. Choose an index `i` where `num[i] == '?'`.
2. Replace ... | It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next |
Python3 solution: top down DP: trim down the parameter set to get accepted | sum-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI thought of DP at once, and it will TLE if I keep both numbers of "?" on the two sides. It will be also be the case for the left and right sums.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe base case for DP i... | 0 | Alice and Bob take turns playing a game, with **Alice** **starting first**.
You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`:
1. Choose an index `i` where `num[i] == '?'`.
2. Replace ... | It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next |
Simple? Python3 Explanation | sum-game | 0 | 1 | # Intuition\nIf players play optimally, Alice will try to push the sides further apart to create an unwinnable scenario for Bob using 0\'s and 9\'s. Bob will counteract these moves also using 0\'s and 9s to keep the sides within 9 before his final move. Since one player will exclusively use 0\'s and the other 9\'s, the... | 0 | Alice and Bob take turns playing a game, with **Alice** **starting first**.
You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`:
1. Choose an index `i` where `num[i] == '?'`.
2. Replace ... | It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next |
Basic Python Solution | sum-game | 0 | 1 | \n# Approach\nThis uses a lot of memory as I utilize a simple approach; define all the conditions and then do all of the math.\nI use the first couple of for loops to set my variables and then I solve using the information gathered\n\nBOB CAN ONLY WIN IF HE GOES LAST AND THE DIFFERENCE BETWEEN THE TWO SIDES IS 9.\nGUES... | 0 | Alice and Bob take turns playing a game, with **Alice** **starting first**.
You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`:
1. Choose an index `i` where `num[i] == '?'`.
2. Replace ... | It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next |
Intuition on Necessary and Sufficient condition: Python3 | sum-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirstly, it should be quite obvious that Bob cannot win if the number of ? is odd, so we will assume that count("?") is even now.\n\nWe will abbreviate LHS and RHS for left and right hand side. This solution will explore the possible th... | 0 | Alice and Bob take turns playing a game, with **Alice** **starting first**.
You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`:
1. Choose an index `i` where `num[i] == '?'`.
2. Replace ... | It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next |
Python 3 Solution | sum-game | 0 | 1 | # Code\n```\nclass Solution:\n def sumGame(self, num: str) -> bool:\n\n numL = list(num[:len(num)//2])\n numR = list(num[len(num)//2:])\n\n sumL = 0\n sumR = 0\n\n qmL = 0\n qmR = 0\n\n for x,y in zip(numL,numR):\n if x=="?":\n qmL += 1\n ... | 0 | Alice and Bob take turns playing a game, with **Alice** **starting first**.
You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`:
1. Choose an index `i` where `num[i] == '?'`.
2. Replace ... | It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.