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 |
|---|---|---|---|---|---|---|---|
[PYTHON] Comments | Simple | minimum-number-of-moves-to-seat-everyone | 0 | 1 | ```\nclass Solution:\n def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n seats = sorted(seats)\n students = sorted(students)\n # redefine the varaibles to be sorted [min->max]\n\n counter = 0\n # set up the counter for amount of moves\n\n for x in ran... | 2 | There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student.
You may perform the following move any number of times:
* ... | Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt |
Python Easiest Solution With Explanation | Sorting | Beg to adv | minimum-number-of-moves-to-seat-everyone | 0 | 1 | ```python\nclass Solution:\n def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n total_moves = 0 # taking a int variable to store the value\n sorted_seats = sorted(seats) # sorting the seat list\n sorted_students = sorted(students) #sorting the student list\n \n ... | 4 | There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student.
You may perform the following move any number of times:
* ... | Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt |
O(n) counting sort in Python | minimum-number-of-moves-to-seat-everyone | 0 | 1 | trivial `O(nlogn)` solution, using `sort()` w/o hesitation:\n```python\nclass Solution:\n def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n seats.sort()\n students.sort()\n return sum(abs(seat - student) for seat, student in zip(seats, students))\n```\n`O(m+n)` solution, ... | 9 | There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student.
You may perform the following move any number of times:
* ... | Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt |
Python || 99.81% Faster || 5 Lines || Sorting | minimum-number-of-moves-to-seat-everyone | 0 | 1 | ```\nclass Solution:\n def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n seats.sort()\n students.sort()\n c,n=0,len(seats)\n for i in range(n): c+=abs(seats[i]-students[i])\n return c\n```\n\n**Upvote if you like the solution or ask if there is any query** | 4 | There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student.
You may perform the following move any number of times:
* ... | Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt |
✅ 99.81% 2-Approaches RegEx & Iterative Count | remove-colored-pieces-if-both-neighbors-are-the-same-color | 1 | 1 | # Interview Guide: "Remove Colored Pieces if Both Neighbors are the Same Color" Problem\n\n## Problem Understanding\n\nIn the "Remove Colored Pieces if Both Neighbors are the Same Color" problem, you are given a string `colors` where each piece is colored either by \'A\' or by \'B\'. Alice and Bob play a game where the... | 41 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
✅96.44%🔥Easy Solution🔥Game Theory & Greedy | remove-colored-pieces-if-both-neighbors-are-the-same-color | 1 | 1 | # Problem Explanation:\n#### In this problem, you are given a string colors representing a line of colored pieces, where each piece is either colored \'A\' or \'B\'. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. Alice goes first, and they have certain rules for removi... | 130 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
100% Acceptance rate with O(n) Solution - Detailed explanation Ever Check it out | remove-colored-pieces-if-both-neighbors-are-the-same-color | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem presents a game played between Alice and Bob on a line of colored pieces, represented by the string colors. Each piece is colored either \'A\' or \'B\', and the players take alternating turns to remove pieces according to cert... | 5 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
✅Easy explanation ever - O(n) solution | remove-colored-pieces-if-both-neighbors-are-the-same-color | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this code is to determine the winner of a game played by Alice and Bob, where they take alternating turns removing pieces based on specific rules about adjacent colors in the input string.\n\n---\n\n# Approach\n<!-- D... | 5 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
Video Solution | Explanation With Drawings | In Depth | C++ | Java | Python 3 | remove-colored-pieces-if-both-neighbors-are-the-same-color | 1 | 1 | # Intuition and approach discussed in detail in video solution\nhttps://youtu.be/Pkywd65nA6Q\n\n# Code\nC++\n```\nclass Solution {\npublic:\n bool winnerOfGame(string colors) {\n int threeA = 0;\n int threeB = 0;\n int sz = colors.size();\n for(int indx = 1; indx < sz - 1; indx++){\n ... | 3 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
🐍😱 Really Scary Python One-Liner! 🎃 | remove-colored-pieces-if-both-neighbors-are-the-same-color | 0 | 1 | **Faster than 98.94% of all solutions**\n\n# Code\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n return sum((len(i) - 2)*(1 if i[0] is \'A\' else -1) for i in filter(lambda x: len(x) > 2, colors.replace(\'AB\', \'AxB\').replace(\'BA\', \'BxA\').split("x"))) > 0\n``` | 2 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
✅ O(n) Solution with detailed explanation ever - Beats 100% with runtime and memory acceptance 😎 | remove-colored-pieces-if-both-neighbors-are-the-same-color | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks us to determine the winner of a game played by Alice and Bob based on certain rules about removing pieces from a string. Alice can only remove \'A\' pieces if both neighbors are also \'A\', and Bob can only remove \'B\' p... | 5 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
🔥Beats 100% | ✅ Line by Line Expl. | [PY/Java/C++/C#/C/JS/Rust/Go] | remove-colored-pieces-if-both-neighbors-are-the-same-color | 1 | 1 | ```python []\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n totalA = 0 # Initialize a variable to store the total points of player A.\n totalB = 0 # Initialize a variable to store the total points of player B.\n currA = 0 # Initialize a variable to count the current consec... | 2 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
Most optimal solution with complete exaplanation | remove-colored-pieces-if-both-neighbors-are-the-same-color | 1 | 1 | \n# Approach\nThe solution iterates through the input string colors. For each position i, it checks if the character at that position and its neighboring characters (at positions i-1 and i+1) satisfy the conditions mentioned in the game rules. If the conditions are met, Alice or Bob can make a move, and their correspon... | 2 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
NOOB CODE : Easy to Understand | remove-colored-pieces-if-both-neighbors-are-the-same-color | 0 | 1 | # Approach\n\n1. It initializes two variables `al` and `bo` to 0 to keep track of the number of consecutive colors for player \'A\' and player \'B\', respectively.\n\n2. It then iterates through the string `colors` from the second character (index 1) to the second-to-last character (index `len(colors) - 2`).\n\n3. Insi... | 2 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
🚀Count Solution || Explained Intuition || Commented Code🚀 | remove-colored-pieces-if-both-neighbors-are-the-same-color | 1 | 1 | # Problem Description\nIn brief, The problem involves a **game** between `Alice` and `Bob` where they take **turns** **removing** pieces from a line of `A` and `B` colored pieces. `Alice` can only remove `A` pieces if **both** neighbors are also `A`, and `Bob` can only remove `B` pieces if **both** neighbors are `B`. T... | 99 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
🐢Slow and Unintuitive Python Solution | Slower than 95%🐢 | remove-colored-pieces-if-both-neighbors-are-the-same-color | 0 | 1 | \nThe top solution explains how this game is not very complicated and you can determine the winner by counting the number of As and Bs. This is like a more complicated version of that solution.\uD83D\uDE0E \n\n```\nclass Solution:\n def winnerOfGame(self, colors: str) -> bool:\n count = 0 # 0 if Alice\'s turn... | 1 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
Simple Approach and Answer. No fancy code | remove-colored-pieces-if-both-neighbors-are-the-same-color | 0 | 1 | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSimply we can count the number of times Alice can pop and the number of times Bob can pop. And return whether Alice has the more count or not.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Spa... | 1 | There are `n` pieces arranged in a line, and each piece is colored either by `'A'` or by `'B'`. You are given a string `colors` of length `n` where `colors[i]` is the color of the `ith` piece.
Alice and Bob are playing a game where they take **alternating turns** removing pieces from the line. In this game, Alice move... | Which type of traversal lets you find the distance from a point? Try using a Breadth First Search. |
Python bfs || fast and very easy to understand | the-time-when-the-network-becomes-idle | 0 | 1 | The idea is very simple:\n1. First we calculate the shortest latency ( amount of time it takes for a message to reach the master server plus the time it takes for a reply to reach back the server ) for every node.\n2. Then from their patience time, we calculate for each node, the last time it sends a message before it... | 1 | There is a network of `n` servers, labeled from `0` to `n - 1`. You are given a 2D integer array `edges`, where `edges[i] = [ui, vi]` indicates there is a message channel between servers `ui` and `vi`, and they can pass **any** number of messages to **each other** directly in **one** second. You are also given a **0-in... | Bob can always make the total sum of both sides equal in mod 9. Why does the difference between the number of question marks on the left and right side matter? |
Clear BFS solution (beats 100% Python, 96.5% Java) | the-time-when-the-network-becomes-idle | 1 | 1 | # Intuition\nAfter using BFS to determine the distance between the start node and every other node, we can calculate when the last messages will be sent and received.\n\n# Approach\n1. Convert the edge list into an adjacency list.\n2. Use BFS to compute the distance from the start node to every other node.\n3. Use a he... | 2 | There is a network of `n` servers, labeled from `0` to `n - 1`. You are given a 2D integer array `edges`, where `edges[i] = [ui, vi]` indicates there is a message channel between servers `ui` and `vi`, and they can pass **any** number of messages to **each other** directly in **one** second. You are also given a **0-in... | Bob can always make the total sum of both sides equal in mod 9. Why does the difference between the number of question marks on the left and right side matter? |
[Python3] graph | the-time-when-the-network-becomes-idle | 0 | 1 | \n```\nclass Solution:\n def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:\n graph = {}\n for u, v in edges: \n graph.setdefault(u, []).append(v)\n graph.setdefault(v, []).append(u)\n \n dist = [-1]*len(graph)\n dist[0] = 0 \n ... | 5 | There is a network of `n` servers, labeled from `0` to `n - 1`. You are given a 2D integer array `edges`, where `edges[i] = [ui, vi]` indicates there is a message channel between servers `ui` and `vi`, and they can pass **any** number of messages to **each other** directly in **one** second. You are also given a **0-in... | Bob can always make the total sum of both sides equal in mod 9. Why does the difference between the number of question marks on the left and right side matter? |
Python3 || Shortest Path | the-time-when-the-network-becomes-idle | 0 | 1 | # Intuition\n- Shortest Path to trace the distance to each vertex to calculcate the distance\n\n# Approach\n- Shortest Path to calculate the time take to reach vertex\n- Calculate the last packet that would leave the node due to no response\n- Calculate it\'s arrival\n\n# Complexity\n- Time complexity:\n- O(V^2) worst ... | 0 | There is a network of `n` servers, labeled from `0` to `n - 1`. You are given a 2D integer array `edges`, where `edges[i] = [ui, vi]` indicates there is a message channel between servers `ui` and `vi`, and they can pass **any** number of messages to **each other** directly in **one** second. You are also given a **0-in... | Bob can always make the total sum of both sides equal in mod 9. Why does the difference between the number of question marks on the left and right side matter? |
Python BFS | the-time-when-the-network-becomes-idle | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind distance from each data node to master node, then use some math to calculate how long does it take for a data server to finish sending messages, taken into consideration its patience. \n\n# Complexity\n- Time complexity:\n<!-- Add yo... | 0 | There is a network of `n` servers, labeled from `0` to `n - 1`. You are given a 2D integer array `edges`, where `edges[i] = [ui, vi]` indicates there is a message channel between servers `ui` and `vi`, and they can pass **any** number of messages to **each other** directly in **one** second. You are also given a **0-in... | Bob can always make the total sum of both sides equal in mod 9. Why does the difference between the number of question marks on the left and right side matter? |
[Python3] binary search | kth-smallest-product-of-two-sorted-arrays | 0 | 1 | \n```\nclass Solution:\n def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:\n \n def fn(val):\n """Return count of products <= val."""\n ans = 0\n for x in nums1: \n if x < 0: ans += len(nums2) - bisect_left(nums2, ceil(val/x... | 9 | Given two **sorted 0-indexed** integer arrays `nums1` and `nums2` as well as an integer `k`, return _the_ `kth` _(**1-based**) smallest product of_ `nums1[i] * nums2[j]` _where_ `0 <= i < nums1.length` _and_ `0 <= j < nums2.length`.
**Example 1:**
**Input:** nums1 = \[2,5\], nums2 = \[3,4\], k = 2
**Output:** 8
**Exp... | Consider a new graph where each node is one of the old nodes at a specific time. For example, node 0 at time 5. You need to find the shortest path in the new graph. |
Python 3 AC Solution with detailed math derivation | kth-smallest-product-of-two-sorted-arrays | 0 | 1 | ```\nclass Solution:\n def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:\n """\n Binary Search\n find first number that makes countSmallerOrEqual(number) >= k\n return number\n """\n boundary = [nums1[0]*nums2[0], nums1[0] * nums2[-1], nums1[-1... | 2 | Given two **sorted 0-indexed** integer arrays `nums1` and `nums2` as well as an integer `k`, return _the_ `kth` _(**1-based**) smallest product of_ `nums1[i] * nums2[j]` _where_ `0 <= i < nums1.length` _and_ `0 <= j < nums2.length`.
**Example 1:**
**Input:** nums1 = \[2,5\], nums2 = \[3,4\], k = 2
**Output:** 8
**Exp... | Consider a new graph where each node is one of the old nodes at a specific time. For example, node 0 at time 5. You need to find the shortest path in the new graph. |
simple python | check-if-numbers-are-ascending-in-a-sentence | 0 | 1 | \nclass Solution:\n def areNumbersAscending(self, s: str) -> bool:\n s=s.split(" ")\n l=[]\n for i in s:\n if i.isdigit():\n l.append(int(i))\n print(l)\n l1=sorted(l)\n if(l==l1):\n s1=set(l1)\n if(len(s1)==len(l1)):\n ... | 1 | A sentence is a list of **tokens** separated by a **single** space with no leading or trailing spaces. Every token is either a **positive number** consisting of digits `0-9` with no leading zeros, or a **word** consisting of lowercase English letters.
* For example, `"a puppy has 2 eyes 4 legs "` is a sentence with ... | If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array. |
[Python3] 2-line | check-if-numbers-are-ascending-in-a-sentence | 0 | 1 | \n```\nclass Solution:\n def areNumbersAscending(self, s: str) -> bool:\n nums = [int(w) for w in s.split() if w.isdigit()]\n return all(nums[i-1] < nums[i] for i in range(1, len(nums)))\n``` | 29 | A sentence is a list of **tokens** separated by a **single** space with no leading or trailing spaces. Every token is either a **positive number** consisting of digits `0-9` with no leading zeros, or a **word** consisting of lowercase English letters.
* For example, `"a puppy has 2 eyes 4 legs "` is a sentence with ... | If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array. |
One line Python solution | check-if-numbers-are-ascending-in-a-sentence | 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 sentence is a list of **tokens** separated by a **single** space with no leading or trailing spaces. Every token is either a **positive number** consisting of digits `0-9` with no leading zeros, or a **word** consisting of lowercase English letters.
* For example, `"a puppy has 2 eyes 4 legs "` is a sentence with ... | If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array. |
Beat 94.70% 23 ms Python 3 | check-if-numbers-are-ascending-in-a-sentence | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def areNumbersAscending(self, s: str) -> bool:\n b = 0\n for i in s.split():\n if i.isdigit():\n if int(i) <= b: return False\n else: b = int(i)\n return True\n\n``` | 2 | A sentence is a list of **tokens** separated by a **single** space with no leading or trailing spaces. Every token is either a **positive number** consisting of digits `0-9` with no leading zeros, or a **word** consisting of lowercase English letters.
* For example, `"a puppy has 2 eyes 4 legs "` is a sentence with ... | If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array. |
Python simple solution | check-if-numbers-are-ascending-in-a-sentence | 0 | 1 | **Python :**\n\n```\ndef areNumbersAscending(self, s: str) -> bool:\n\tprev = -1\n\n\tfor w in s.split():\n\t\tif w.isdigit():\n\t\t\tif int(w) <= prev:\n\t\t\t\treturn False\n\t\t\tprev = int(w)\n\n\treturn True\n```\n\n**Like it ? please upvote !** | 13 | A sentence is a list of **tokens** separated by a **single** space with no leading or trailing spaces. Every token is either a **positive number** consisting of digits `0-9` with no leading zeros, or a **word** consisting of lowercase English letters.
* For example, `"a puppy has 2 eyes 4 legs "` is a sentence with ... | If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array. |
Very simple python solution - O(n) | check-if-numbers-are-ascending-in-a-sentence | 0 | 1 | \n# Code\n```\nclass Solution:\n def areNumbersAscending(self, s: str) -> bool:\n l = s.split(\' \') # split string into list of words\n max = 0 # keep track of current maximum\n for i in l:\n if i.isdigit(): # check if i is a number\n if int(i) <= max: # check if the n... | 2 | A sentence is a list of **tokens** separated by a **single** space with no leading or trailing spaces. Every token is either a **positive number** consisting of digits `0-9` with no leading zeros, or a **word** consisting of lowercase English letters.
* For example, `"a puppy has 2 eyes 4 legs "` is a sentence with ... | If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array. |
Python3|| Beats 93.33% || Simple solution & O(n*logn). | check-if-numbers-are-ascending-in-a-sentence | 0 | 1 | # **Please do upvote if you like the solution.**\n# Code\n```\nclass Solution:\n def areNumbersAscending(self, s: str) -> bool:\n l=[]\n for i in s.split():\n if i.isnumeric():\n l.append(int(i))\n return l == sorted(set(l))\n``` | 2 | A sentence is a list of **tokens** separated by a **single** space with no leading or trailing spaces. Every token is either a **positive number** consisting of digits `0-9` with no leading zeros, or a **word** consisting of lowercase English letters.
* For example, `"a puppy has 2 eyes 4 legs "` is a sentence with ... | If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array. |
Python decorator | simple-bank-system | 0 | 1 | \n# Code\n```\ndef validator(function):\n def wrapper(self, *args, **kwargs):\n if len(args) == 3:\n account1, account2, money = args\n if (account1 not in self.balance_map) or (account2 not in self.balance_map):\n return False\n elif len(args) == 2:\n ac... | 1 | You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has `n` accounts numbered from `1` to `n`. The initial balance of each account is stored in a **0-indexed** integer array `balance`, with the `(i + 1)th` account ha... | First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it. |
[Python3] just do what's told | simple-bank-system | 0 | 1 | \n```\nclass Bank:\n\n def __init__(self, balance: List[int]):\n self.balance = balance\n\n def transfer(self, account1: int, account2: int, money: int) -> bool:\n if self.withdraw(account1, money): \n if self.deposit(account2, money): return True \n self.deposit(account1, mone... | 8 | You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has `n` accounts numbered from `1` to `n`. The initial balance of each account is stored in a **0-indexed** integer array `balance`, with the `(i + 1)th` account ha... | First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it. |
Easy Python Solution | Faster than 100% | With Comments | simple-bank-system | 0 | 1 | # Easy Python Solution | Faster than 100% | With Comments\n\n**Runtime: 673 ms, faster than 100.00% of Python3 online submissions for Simple Bank System.\nMemory Usage: 43.8 MB.**\n\n```\nclass Bank:\n\n def __init__(self, bal: List[int]):\n self.store = bal # storage list\n\n\n def transfer(self, a1: in... | 2 | You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has `n` accounts numbered from `1` to `n`. The initial balance of each account is stored in a **0-indexed** integer array `balance`, with the `(i + 1)th` account ha... | First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it. |
✅ Easy to understand Python solution | simple-bank-system | 0 | 1 | # Code\n```\nclass Bank:\n\n def __init__(self, balance: List[int]):\n self.balance = balance\n \n def transfer(self, account1: int, account2: int, money: int) -> bool:\n if account1 <= len(self.balance) and account2 <= len(self.balance) and self.balance[account1 - 1] >= money:\n s... | 0 | You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has `n` accounts numbered from `1` to `n`. The initial balance of each account is stored in a **0-indexed** integer array `balance`, with the `(i + 1)th` account ha... | First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it. |
python3 simulation | simple-bank-system | 0 | 1 | \n\n# Code\n```\nclass Bank:\n\n def __init__(self, balance: List[int]):\n self.balance = balance\n\n def transfer(self, account1: int, account2: int, money: int) -> bool:\n if account1 > len(self.balance) or account2 > len(self.balance):\n return False\n if self.balance[account1-1... | 0 | You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has `n` accounts numbered from `1` to `n`. The initial balance of each account is stored in a **0-indexed** integer array `balance`, with the `(i + 1)th` account ha... | First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it. |
Easy Python Solution | simple-bank-system | 0 | 1 | # Code\n```\nclass Bank:\n\n def __init__(self, balance: List[int]):\n self.bankAccounts = balance\n self.length = len(self.bankAccounts)\n \n\n def transfer(self, account1: int, account2: int, money: int) -> bool:\n if 1 <= account1 <= self.length and 1 <= account2 <= self.length:\n ... | 0 | You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has `n` accounts numbered from `1` to `n`. The initial balance of each account is stored in a **0-indexed** integer array `balance`, with the `(i + 1)th` account ha... | First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it. |
Hashmap | count-number-of-maximum-bitwise-or-subsets | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given an integer array `nums`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_.
An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. Two su... | For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit. |
[Python3] top-down dp | count-number-of-maximum-bitwise-or-subsets | 0 | 1 | \n```\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n target = reduce(or_, nums)\n \n @cache\n def fn(i, mask): \n """Return number of subsets to get target."""\n if mask == target: return 2**(len(nums)-i)\n if i == len(nums): ret... | 9 | Given an integer array `nums`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_.
An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. Two su... | For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit. |
Easy python solution using recursion and backtracking | count-number-of-maximum-bitwise-or-subsets | 0 | 1 | # Code\n```\nclass Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n def subs(idx,nums,N,lst,l):\n if idx>=N:\n val=0\n for i in lst:\n val |= i\n l.append(val)\n return\n lst.append(nums[idx]... | 2 | Given an integer array `nums`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_.
An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. Two su... | For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit. |
Python3 | Solved using Recursion + Backtracking | count-number-of-maximum-bitwise-or-subsets | 0 | 1 | ```\nclass Solution:\n #Let n = len(nums) array!\n #Time-Complexity: O(n * 2^n), since we make 2^n rec. calls to generate\n #all 2^n different subsets and for each rec. call, we call helper function that\n #computes Bitwise Or Lienarly!\n #Space-Complexity: O(n), since max stack depth is n!\n def coun... | 1 | Given an integer array `nums`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_.
An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. Two su... | For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit. |
Backtracking solution | count-number-of-maximum-bitwise-or-subsets | 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`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_.
An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. Two su... | For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit. |
BackTracking using python Easy Solution..! | count-number-of-maximum-bitwise-or-subsets | 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`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_.
An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. Two su... | For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit. |
python straightforward backtracking solution | count-number-of-maximum-bitwise-or-subsets | 0 | 1 | # Code\n```\nclass Solution:\n def backtracking(self, nums, startIndex, path, result):\n if len(path) > 0: result.append(path[:])\n for i in range(startIndex, len(nums)):\n self.backtracking(nums, i + 1, path + [nums[i]], result)\n \n def find_or_max_count(self, subsets):\n max_... | 0 | Given an integer array `nums`, find the **maximum** possible **bitwise OR** of a subset of `nums` and return _the **number of different non-empty subsets** with the maximum bitwise OR_.
An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. Two su... | For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit. |
[Python3] Dijkstra & BFS | second-minimum-time-to-reach-destination | 0 | 1 | \n```\nclass Solution:\n def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:\n graph = [[] for _ in range(n)]\n for u, v in edges: \n graph[u-1].append(v-1)\n graph[v-1].append(u-1)\n pq = [(0, 0)]\n seen = [[] for _ in range(n)]\n... | 9 | A city is represented as a **bi-directional connected** graph with `n` vertices where each vertex is labeled from `1` to `n` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every ve... | Use binary search on the answer. You can get l/m branches of length m from a branch with length l. |
heap based solution | second-minimum-time-to-reach-destination | 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 city is represented as a **bi-directional connected** graph with `n` vertices where each vertex is labeled from `1` to `n` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every ve... | Use binary search on the answer. You can get l/m branches of length m from a branch with length l. |
[Python] BFS solution with Japanese explanation. | second-minimum-time-to-reach-destination | 0 | 1 | # Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n- 2nd\u6700\u77ED\u3082\u7BA1\u7406\u3059\u308B\u3088\u3046\u306BBFS\uFF08DP\uFF09\u3092\u884C\u3046\u3002\n - BFS\u3092\u884C\u3063\u3066\u3044\u308B\u304C\u3001\u672C\u8CEA\u7684\u306B\u306F\u52D5\u7684\u8A08\u753B\u6CD5\u... | 0 | A city is represented as a **bi-directional connected** graph with `n` vertices where each vertex is labeled from `1` to `n` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every ve... | Use binary search on the answer. You can get l/m branches of length m from a branch with length l. |
Simple BFS in Python, Faster than 95% | second-minimum-time-to-reach-destination | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this problem, a vertex can be visited more than one time. In fact, only the first two visits should be considered since the goal is to find the second shortest path. This is the key to solve this problem efficiently. \n\n# Approach\n<!... | 0 | A city is represented as a **bi-directional connected** graph with `n` vertices where each vertex is labeled from `1` to `n` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every ve... | Use binary search on the answer. You can get l/m branches of length m from a branch with length l. |
Python (Simple modified Dijkstra's algorithm) | second-minimum-time-to-reach-destination | 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 city is represented as a **bi-directional connected** graph with `n` vertices where each vertex is labeled from `1` to `n` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every ve... | Use binary search on the answer. You can get l/m branches of length m from a branch with length l. |
Python | Easy Solution✅ | number-of-valid-words-in-a-sentence | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n sentence_list = sentence.split()\n count = 0\n for i, word in enumerate(sentence_list):\n valid = True\n hyphen_count = 0 \n for j, letter in enumerate(word):\n ... | 6 | A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`.
A token is a valid word if **all three** of the ... | Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If ... |
✔️ PYTHON || EXPLAINED || ;] CORNER CASE | number-of-valid-words-in-a-sentence | 0 | 1 | **UPVOTE IF HELPFuuL**\n\nSolution is just implementation provided below.\n\nThe case that people miss is ```"example-!"``` -> where there is hypen and puntuation at the end.\n\n```\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n a = list(sentence.split())\n res=0\n punc = ... | 6 | A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`.
A token is a valid word if **all three** of the ... | Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If ... |
[Python3] check words | number-of-valid-words-in-a-sentence | 0 | 1 | \n```\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n \n def fn(word): \n """Return true if word is valid."""\n seen = False \n for i, ch in enumerate(word): \n if ch.isdigit() or ch in "!.," and i != len(word)-1: return False\n ... | 24 | A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`.
A token is a valid word if **all three** of the ... | Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If ... |
Python by regex [w/ Comment] | number-of-valid-words-in-a-sentence | 0 | 1 | Python by [regula expression aka regex](https://docs.python.org/3/library/re.html)\n\n[Online regex debugger](https://regex101.com/)\n\n---\n\n```\nimport re\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n \n # parse and get each word from sentence\n words = sentence.split(... | 7 | A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`.
A token is a valid word if **all three** of the ... | Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If ... |
python with regex | number-of-valid-words-in-a-sentence | 0 | 1 | ```\nimport re\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n count = 0\n pattern = "^([a-z]+(-?[a-z]+)?)?(!|\\.|,)?$"\n sentence_list = sentence.split()\n for word in sentence_list:\n result = re.match(pattern, word)\n if result:\n ... | 2 | A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`.
A token is a valid word if **all three** of the ... | Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If ... |
Python | REGEX pattern matching Explained | Faster than 98.86% | number-of-valid-words-in-a-sentence | 0 | 1 | A rule of thumb is that when you need to filter strings based on multiple conditions, `regex` will be your friend. The regex pattern we want to search for is: \n```\n(^[a-z]+(-[a-z]+)?)?[,.!]?$\n```\nThis pattern consists of many parts: \n\n- `^` denotes the beginning of a string.\n- `[a-z]` matches any character in t... | 3 | A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`.
A token is a valid word if **all three** of the ... | Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If ... |
Fastest Python Solution | 100%, 35ms | number-of-valid-words-in-a-sentence | 0 | 1 | # Fastest Python Solution | 100%, 35ms\n**Runtime: 35 ms, faster than 100.00% of Python3 online submissions for Number of Valid Words in a Sentence.\nMemory Usage: 14.3 MB.**\n```\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n sen = sentence.split()\n r, m = 0, 0\n _digits... | 5 | A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`.
A token is a valid word if **all three** of the ... | Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If ... |
python, net | number-of-valid-words-in-a-sentence | 0 | 1 | # Code\n```\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n ls = list(sentence.split())\n punctuations = set("!., ")\n \n cnt = 0\n for i in ls:\n alphabet_cnt = 0\n numbers_cnt = 0\n punc_cnt = 0\n hyphens_cnt = 0\n... | 0 | A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`.
A token is a valid word if **all three** of the ... | Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If ... |
Two line solution with using regex | number-of-valid-words-in-a-sentence | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | A sentence consists of lowercase letters (`'a'` to `'z'`), digits (`'0'` to `'9'`), hyphens (`'-'`), punctuation marks (`'!'`, `'.'`, and `','`), and spaces (`' '`) only. Each sentence can be broken down into **one or more tokens** separated by one or more spaces `' '`.
A token is a valid word if **all three** of the ... | Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If ... |
Python Using permutations (very simple solution)-->96% Faster | next-greater-numerically-balanced-number | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def nextBeautifulNumber(self, n: int) -> int:\n from itertools import permutations\n mylist = [1, 22, 122, 333, 1333, 4444, 14444, 22333, 55555, 122333, 155555, 224444, 666666,1224444]\n res=[]\n def digit_combination(a,length):\n a = list(str... | 1 | An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`.
Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._
**Example 1:**
**Input:** n = 1
**Output:** 22
**Explanation:**... | Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application |
[Python3] brute-force | next-greater-numerically-balanced-number | 0 | 1 | \n```\nclass Solution:\n def nextBeautifulNumber(self, n: int) -> int:\n while True: \n n += 1\n nn = n \n freq = defaultdict(int)\n while nn: \n nn, d = divmod(nn, 10)\n freq[d] += 1\n if all(k == v for k, v in freq.items())... | 3 | An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`.
Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._
**Example 1:**
**Input:** n = 1
**Output:** 22
**Explanation:**... | Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application |
Python - Generate Numeric Balanced Numbers with Prune | next-greater-numerically-balanced-number | 0 | 1 | **Idea**\n\n- The idea is that we generate all possible numeric balanced numbers with numLen start from |n|.\n- While backtracking to generate we can prune some invalid combination, they are\n- if counter[d] >= d: continue # Prune if number of occurrences of d is greater than d\n- if counter[d] + (numLen - i) < d: cont... | 0 | An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`.
Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._
**Example 1:**
**Input:** n = 1
**Output:** 22
**Explanation:**... | Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application |
Python3|| backtracking | next-greater-numerically-balanced-number | 0 | 1 | # Intuition\n- We will need to know all the numbers that we can use, So hence I have created a method getNums\n- Get all the permutations with the values we can use and get the lowest among the values that is greater than n\n\n# Approach\n- Intuition pretty much explains the approach\n\n# Complexity\n- Time complexity:... | 0 | An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`.
Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._
**Example 1:**
**Input:** n = 1
**Output:** 22
**Explanation:**... | Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application |
Solution Using Dictionary | next-greater-numerically-balanced-number | 0 | 1 | # Intuition\nCreate function to check whether a number is balanced. and then iterate from n+1 to find the next balanced number.\n\n# Approach\nisbalanced function checks whether the digit value is equal to the number of occurences using a dictionary and then returns True or False.\n\n# Complexity\n- Time complexity:O(n... | 0 | An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`.
Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._
**Example 1:**
**Input:** n = 1
**Output:** 22
**Explanation:**... | Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application |
Python Easy Solution | next-greater-numerically-balanced-number | 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 | An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`.
Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._
**Example 1:**
**Input:** n = 1
**Output:** 22
**Explanation:**... | Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application |
python | next-greater-numerically-balanced-number | 0 | 1 | Not an intuitive question\n# Code\n```\nclass Solution:\n def nextBeautifulNumber(self, n: int) -> int:\n i = n+1\n while True:\n if i % 10 == 0:\n i += 1\n continue\n\n c = Counter(str(i))\n \n flag = False\n for k, ... | 0 | An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`.
Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._
**Example 1:**
**Input:** n = 1
**Output:** 22
**Explanation:**... | Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application |
Easy to understand | |Next Greater Numerically Balanced Number Simple iterative Solution | next-greater-numerically-balanced-number | 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 | An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`.
Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._
**Example 1:**
**Input:** n = 1
**Output:** 22
**Explanation:**... | Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application |
Python3 brute force | next-greater-numerically-balanced-number | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def nextBeautifulNumber(self, n: int) -> int:\n \n def isValid(x):\n count=Counter(str(x))\n for k,v in count.items():\n if int(k)!=v:\n return False\n \n return True\n\n \n st... | 0 | An integer `x` is **numerically balanced** if for every digit `d` in the number `x`, there are **exactly** `d` occurrences of that digit in `x`.
Given an integer `n`, return _the **smallest numerically balanced** number **strictly greater** than_ `n`_._
**Example 1:**
**Input:** n = 1
**Output:** 22
**Explanation:**... | Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application |
✔ Python3 Solution | DFS | O(n) | count-nodes-with-the-highest-score | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def countHighestScoreNodes(self, parents: List[int]) -> int:\n n = len(parents)\n scores = [1] * n\n graph = [[] for _ in range(n)]\n for e, i in enumerate(parents):\n if e... | 1 | There is a **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
Python Easy Recursive Solution | count-nodes-with-the-highest-score | 0 | 1 | ## Code\n```\nclass Solution:\n def countHighestScoreNodes(self, parents: List[int]) -> int:\n\n sizes = [[0]*2 for _ in range(len(parents))]\n dic = defaultdict(list)\n\n def rec(root):\n\n if not dic[root]:\n return 1\n\n if len(dic[root]) == 1:\n ... | 1 | There is a **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
Python 3 | Graph, DFS, Post-order Traversal, O(N) | Explanation | count-nodes-with-the-highest-score | 0 | 1 | ### Explanation\n- Intuition: Maximum product of 3 branches, need to know how many nodes in each branch, use `DFS` to start with\n- Build graph\n- Find left, right, up (number of nodes) for each node\n\t- left: use recursion\n\t- right: use recursion\n\t- up: `n - 1 - left - right`\n- Calculate score store in a dictina... | 81 | There is a **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
✔️ PYTHON || EXPLAINED || ;] | count-nodes-with-the-highest-score | 0 | 1 | **UPVOTE IF HELPFuuL**\n\n**Observation** : \nscore = ```number of above nodes * number of nodes of 1 child * number of nodes ofother child```\n\nWe are provided with the parents of nodes, For convenience we keep mapping of chilren of nodes.\n\n* First task : Create a dictionary to keep the children of nodes.\n* Second... | 5 | There is a **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
[Python3] post-order dfs | count-nodes-with-the-highest-score | 0 | 1 | \n```\nclass Solution:\n def countHighestScoreNodes(self, parents: List[int]) -> int:\n tree = [[] for _ in parents]\n for i, x in enumerate(parents): \n if x >= 0: tree[x].append(i)\n \n freq = defaultdict(int)\n \n def fn(x): \n """Return coun... | 17 | There is a **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
Using DFS | count-nodes-with-the-highest-score | 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 **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
DFS | count-nodes-with-the-highest-score | 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 **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
Simple DFS solution. Runtime > 99%!!! | count-nodes-with-the-highest-score | 0 | 1 | \n```\nclass Solution:\n def dfs(self, root, tree, cnt):\n if not tree[root]:\n cnt[root] ... | 0 | There is a **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
Iterate with stack --- O(n), 98% Time + 100% space | count-nodes-with-the-highest-score | 0 | 1 | # Intuition\nFor every node removed there will always be 1, 2 or 3 subtrees: One for each child (2 at most) and one for the parent.\nTo compute a score of a node V, we must know the size of each of its child nodes AND the size of the upper part of the free.\nNote: The size of the upper part is: `size[0] - size[v]` (siz... | 0 | There is a **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
Python3 Solution Easy to Understand with O(n) | DFS | count-nodes-with-the-highest-score | 0 | 1 | # Code\n```\nclass Solution:\n def countHighestScoreNodes(self, parents: List[int]) -> int:\n n = len(parents)\n\n cntChilds = [0 for _ in range(n)]\n # buld graph\n graph = [[] for _ in range(n)]\n for i in range(1,n):\n graph[parents[i]].append(i)\n ##\n ... | 0 | There is a **binary** tree rooted at `0` consisting of `n` nodes. The nodes are labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `parents` representing the tree, where `parents[i]` is the parent of node `i`. Since node `0` is the root, `parents[0] == -1`.
Each node has a **score**. To find the ... | Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive. |
Original Heap-Based Approach | parallel-courses-iii | 0 | 1 | # Complexity\n- Time complexity: $$O(n*log(n)*c)$$, n - number of courses, c - avg number of connections between courses.\n\n- Space complexity: $$O(n)$$.\n\n# Code\n```\nclass Solution:\n def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:\n # List of successors\n nodeTo... | 5 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Further... | Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n. |
✅☑[C++/Java/Python/JavaScript] || Beats 100% || 2 Approaches || EXPLAINED🔥 | parallel-courses-iii | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Sort + Kahn\'s Algorithm)***\n\n***Kahn\'s Algorithm :***\nKahn\'s algorithm, also known as Kahn\'s topological sort algorithm, is used to find a topological ordering of the nodes in a directed acyclic graph (... | 4 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Further... | Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n. |
✨✅💯 Simple Solution | Beats 100% | Kahn's Agorithm ✨✅💯 | parallel-courses-iii | 0 | 1 | # Proof:\n\n# Intuition And Approach:\nRelax Time by taking the max of its current value and previous neighbour+time[curr] while applying Kahn\'s Algo ( Toposort using BFS and Indegrees... | 2 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Further... | Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n. |
✅ 92.65% BFS in Directed Acyclic Graph | parallel-courses-iii | 1 | 1 | # Intuition\nWhen we first encounter this problem, it is evident that the courses have dependencies among themselves. The first intuition that should come to mind when seeing such dependencies is a directed graph, where an edge from one course to another signifies a prerequisite relationship. Since the problem guarante... | 34 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Further... | Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n. |
✅98.44%🔥Easy Solution🔥with explanation🔥 | parallel-courses-iii | 1 | 1 | # Problem Explanation: \uD83E\uDDAF\n\n##### You are given a list of courses with prerequisites and a duration for each course. You want to complete all the courses while adhering to the prerequisites. The goal is to minimize the time it takes to complete all the courses.\n\n---\n\n# DFS + Memoization (Top-Down DP): \u... | 77 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Further... | Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n. |
🚀 Topological Sort using Kahn's Algorithm || Explained Intuition🚀 | parallel-courses-iii | 1 | 1 | # Problem Description\n\nGiven an integer `n` representing the number of courses labeled from `1` to `n`, a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` indicates that course `prevCoursej` must be completed before course `nextCoursej` (prerequisite relationship), and a 0-indexed intege... | 35 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Further... | Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n. |
[python3] BFS and keep track of max value of children | parallel-courses-iii | 0 | 1 | ```\nclass Solution:\n def minimumTime(self, n: int, rel: List[List[int]], time: List[int]) -> int:\n indegree = [0]*(n+1)\n maxi = [0]*(n+1)\n ans = 0\n stack = []\n \n G = defaultdict(list)\n \n for s,e in rel:\n indegree[e] += 1\n G[s].... | 1 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Further... | Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n. |
Python || Stack || DFS || Recursive | parallel-courses-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Further... | Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n. |
Python3 Solution | parallel-courses-iii | 0 | 1 | \n```\nclass Solution:\n def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:\n graph=defaultdict(list)\n for required,course in relations:\n graph[course].append(required)\n\n @cache\n def dp (i):\n if not graph.get(i,False):\n ... | 1 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given a 2D integer array `relations` where `relations[j] = [prevCoursej, nextCoursej]` denotes that course `prevCoursej` has to be completed **before** course `nextCoursej` (prerequisite relationship). Further... | Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n. |
Python solution | kth-distinct-string-in-an-array | 0 | 1 | # Code\n```\nclass Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n uni = []\n copies = []\n for item in arr:\n if item not in uni:\n if item in copies:\n pass\n else:\n uni.append(item)\n ... | 1 | A **distinct string** is a string that is present only **once** in an array.
Given an array of strings `arr`, and an integer `k`, return _the_ `kth` _**distinct string** present in_ `arr`. If there are **fewer** than `k` distinct strings, return _an **empty string**_ `" "`.
Note that the strings are considered in the... | Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same. |
Python Hash Table | kth-distinct-string-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n\n ... | 1 | A **distinct string** is a string that is present only **once** in an array.
Given an array of strings `arr`, and an integer `k`, return _the_ `kth` _**distinct string** present in_ `arr`. If there are **fewer** than `k` distinct strings, return _an **empty string**_ `" "`.
Note that the strings are considered in the... | Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same. |
Easy to Understand , beats 85.8% of solution in Python. Beginner Friendly Solution | kth-distinct-string-in-an-array | 0 | 1 | \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N) is the time complexity as Counter takes O(N) time complexity.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N) is the worst space complexity where all the elements are unique\n\n# Code\n``... | 1 | A **distinct string** is a string that is present only **once** in an array.
Given an array of strings `arr`, and an integer `k`, return _the_ `kth` _**distinct string** present in_ `arr`. If there are **fewer** than `k` distinct strings, return _an **empty string**_ `" "`.
Note that the strings are considered in the... | Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same. |
4 liner code very easy beats 98.33% | kth-distinct-string-in-an-array | 0 | 1 | # Best Code Easy To understand beats 98.33% for true\n\n# Code\n```\nclass Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n for val,c in Counter(arr).items():\n if c==1:\n k-=1\n if k==0: return val\n return ""\n``` | 1 | A **distinct string** is a string that is present only **once** in an array.
Given an array of strings `arr`, and an integer `k`, return _the_ `kth` _**distinct string** present in_ `arr`. If there are **fewer** than `k` distinct strings, return _an **empty string**_ `" "`.
Note that the strings are considered in the... | Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same. |
Python simple 2 lines solution | kth-distinct-string-in-an-array | 0 | 1 | **Python :**\n\n```\ndef kthDistinct(self, arr: List[str], k: int) -> str:\n\tarr = [i for i in arr if arr.count(i) == 1]\n\treturn "" if k > len(arr) else arr[k - 1]\n```\n\n**Like it ? please upvote !** | 27 | A **distinct string** is a string that is present only **once** in an array.
Given an array of strings `arr`, and an integer `k`, return _the_ `kth` _**distinct string** present in_ `arr`. If there are **fewer** than `k` distinct strings, return _an **empty string**_ `" "`.
Note that the strings are considered in the... | Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same. |
[Python3] freq table | kth-distinct-string-in-an-array | 0 | 1 | \n```\nclass Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n freq = Counter(arr)\n for x in arr: \n if freq[x] == 1: k -= 1\n if k == 0: return x\n return ""\n``` | 19 | A **distinct string** is a string that is present only **once** in an array.
Given an array of strings `arr`, and an integer `k`, return _the_ `kth` _**distinct string** present in_ `arr`. If there are **fewer** than `k` distinct strings, return _an **empty string**_ `" "`.
Note that the strings are considered in the... | Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same. |
Python Easy Solution || Hash Table | kth-distinct-string-in-an-array | 0 | 1 | # Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n dic={}\n for i in arr:\n if i in dic:\n dic[i]+=1\n else:\n dic[i]=1\n for i in arr:\n... | 1 | A **distinct string** is a string that is present only **once** in an array.
Given an array of strings `arr`, and an integer `k`, return _the_ `kth` _**distinct string** present in_ `arr`. If there are **fewer** than `k` distinct strings, return _an **empty string**_ `" "`.
Note that the strings are considered in the... | Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same. |
[Python3] binary search | two-best-non-overlapping-events | 0 | 1 | \n```\nclass Solution:\n def maxTwoEvents(self, events: List[List[int]]) -> int:\n time = []\n vals = []\n ans = prefix = 0\n for st, et, val in sorted(events, key=lambda x: x[1]): \n prefix = max(prefix, val)\n k = bisect_left(time, st)-1\n if k >= 0: val... | 15 | You are given a **0-indexed** 2D integer array of `events` where `events[i] = [startTimei, endTimei, valuei]`. The `ith` event starts at `startTimei` and ends at `endTimei`, and if you attend this event, you will receive a value of `valuei`. You can choose **at most** **two** **non-overlapping** events to attend such t... | Sort times by arrival time. for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i. |
📌📌 Heap || very-Easy || Well-Explained 🐍 | two-best-non-overlapping-events | 0 | 1 | ## IDEA:\n**This question is same as https://leetcode.com/problems/maximum-profit-in-job-scheduling/ .**\n\n* In this we have to consider atmost two events. So we will only put the cureent profit in heap.\n\n* Maintain one variable res1 for storing the maximum value among all the events ending before the current event ... | 14 | You are given a **0-indexed** 2D integer array of `events` where `events[i] = [startTimei, endTimei, valuei]`. The `ith` event starts at `startTimei` and ends at `endTimei`, and if you attend this event, you will receive a value of `valuei`. You can choose **at most** **two** **non-overlapping** events to attend such t... | Sort times by arrival time. for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i. |
Binary Search + Right Max | two-best-non-overlapping-events | 0 | 1 | # Complexity\n- Time complexity: $$O(n*log(n))$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code\n```\nclass Solution:\n def maxTwoEvents(self, events: List[List[int]]) -> int:\n START, END, VAL = 0, 1, 2\n\n events.sort()\n maxRightVal = [0]*len(events)\n maxRightVal[-1] = events[-1][VAL]\n ... | 0 | You are given a **0-indexed** 2D integer array of `events` where `events[i] = [startTimei, endTimei, valuei]`. The `ith` event starts at `startTimei` and ends at `endTimei`, and if you attend this event, you will receive a value of `valuei`. You can choose **at most** **two** **non-overlapping** events to attend such t... | Sort times by arrival time. for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i. |
Python heap Sol beats 90% | two-best-non-overlapping-events | 0 | 1 | So, notice that if we sort events, then we always have the left bound increasing. Therefore, we can keep a heap of (right_bound, value) tuples from events that we have seen so far. Whenever the current left bound becomes larger than the right_bound on the stack, that means we can start poppping from the heap to look fo... | 0 | You are given a **0-indexed** 2D integer array of `events` where `events[i] = [startTimei, endTimei, valuei]`. The `ith` event starts at `startTimei` and ends at `endTimei`, and if you attend this event, you will receive a value of `valuei`. You can choose **at most** **two** **non-overlapping** events to attend such t... | Sort times by arrival time. for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i. |
Python Simple + Explanation | plates-between-candles | 0 | 1 | \n# Code\n```\n# Slightly modified Binary search\n# Say you have an array [3, 5, 7, 9, 15] and you have an element\n# 6 and you want to find closest elements on the left and right\n# of 6 in the array. You can run binary search and ultimately\n# r will point to 5 and l will point to 7, i.e r, l gives the boundary\n# Ho... | 1 | There is a long table with a line of plates and candles arranged on top of it. You are given a **0-indexed** string `s` consisting of characters `'*'` and `'|'` only, where a `'*'` represents a **plate** and a `'|'` represents a **candle**.
You are also given a **0-indexed** 2D integer array `queries` where `queries[i... | Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)? |
[Python 3] - Prefix Sum + Binary Search - Simple | plates-between-candles | 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 | There is a long table with a line of plates and candles arranged on top of it. You are given a **0-indexed** string `s` consisting of characters `'*'` and `'|'` only, where a `'*'` represents a **plate** and a `'|'` represents a **candle**.
You are also given a **0-indexed** 2D integer array `queries` where `queries[i... | Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)? |
Python bisect | plates-between-candles | 0 | 1 | A short solution using bisect (built in library bisect [source code](https://github.com/python/cpython/blob/3.10/Lib/bisect.py)):\n\n`p` stores the index for each candle, \n`p[j] - p[i]` returns how many plates there are between the two candles.\n`j - i` returns how many candles are between these two candles\njust be c... | 9 | There is a long table with a line of plates and candles arranged on top of it. You are given a **0-indexed** string `s` consisting of characters `'*'` and `'|'` only, where a `'*'` represents a **plate** and a `'|'` represents a **candle**.
You are also given a **0-indexed** 2D integer array `queries` where `queries[i... | Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.