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 3 (two lines) (beats 100%) (16 ms) (With Explanation) | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | - Start from letter z (two digit numbers) and work backwords to avoid any confusion or inteference with one digit numbers. After replacing all two digit (hashtag based) numbers, we know that the remaining numbers will be simple one digit replacements.\n- Note that ord(\'a\') is 97 which means that chr(97) is \'a\'. Thi... | 138 | There are `n` people and `40` types of hats labeled from `1` to `40`.
Given a 2D integer array `hats`, where `hats[i]` is a list of all hats preferred by the `ith` person.
Return _the number of ways that the `n` people wear different hats to each other_.
Since the answer may be too large, return it modulo `109 + 7`.... | Scan from right to left, in each step of the scanning check whether there is a trailing "#" 2 indexes away. |
Easy Soln | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | # Code\n```\nclass Solution:\n def freqAlphabets(self, s: str) -> str:\n i=0\n st=""\n while i<len(s):\n if i+2<len(s) and s[i+2]=="#":\n st+=chr(96+int(s[i:i+2]))\n i+=2\n else:\n st+=chr(96+int(s[i]))\n i+=1\n ... | 1 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
Easy Soln | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | # Code\n```\nclass Solution:\n def freqAlphabets(self, s: str) -> str:\n i=0\n st=""\n while i<len(s):\n if i+2<len(s) and s[i+2]=="#":\n st+=chr(96+int(s[i:i+2]))\n i+=2\n else:\n st+=chr(96+int(s[i]))\n i+=1\n ... | 1 | There are `n` people and `40` types of hats labeled from `1` to `40`.
Given a 2D integer array `hats`, where `hats[i]` is a list of all hats preferred by the `ith` person.
Return _the number of ways that the `n` people wear different hats to each other_.
Since the answer may be too large, return it modulo `109 + 7`.... | Scan from right to left, in each step of the scanning check whether there is a trailing "#" 2 indexes away. |
Just replace 26 times - STUPID Python solution | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | \n# Code\n```\nclass Solution:\n def freqAlphabets(self, s: str) -> str:\n s = s.replace(\'10#\',\'j\').replace(\'11#\',\'k\').replace(\'12#\',\'l\').replace(\'13#\',\'m\').replace(\'14#\',\'n\').replace(\'15#\',\'o\')\n s = s.replace(\'16#\',\'p\').replace(\'17#\',\'q\').replace(\'18#\',\'r\').replace... | 4 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
Just replace 26 times - STUPID Python solution | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | \n# Code\n```\nclass Solution:\n def freqAlphabets(self, s: str) -> str:\n s = s.replace(\'10#\',\'j\').replace(\'11#\',\'k\').replace(\'12#\',\'l\').replace(\'13#\',\'m\').replace(\'14#\',\'n\').replace(\'15#\',\'o\')\n s = s.replace(\'16#\',\'p\').replace(\'17#\',\'q\').replace(\'18#\',\'r\').replace... | 4 | There are `n` people and `40` types of hats labeled from `1` to `40`.
Given a 2D integer array `hats`, where `hats[i]` is a list of all hats preferred by the `ith` person.
Return _the number of ways that the `n` people wear different hats to each other_.
Since the answer may be too large, return it modulo `109 + 7`.... | Scan from right to left, in each step of the scanning check whether there is a trailing "#" 2 indexes away. |
[Python] Simple and easy solution | 96% faster | help of ascii code | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | ```\nclass Solution:\n def freqAlphabets(self, s: str) -> str:\n ans = ""\n i = len(s)-1\n while i>=0:\n if s[i]=="#":\n ans = ans + chr(int(s[i-2:i])+96)\n i=i-2\n else:\n ans = ans + chr(int(s[i])+96)\n i -= 1\n ... | 29 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
[Python] Simple and easy solution | 96% faster | help of ascii code | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | ```\nclass Solution:\n def freqAlphabets(self, s: str) -> str:\n ans = ""\n i = len(s)-1\n while i>=0:\n if s[i]=="#":\n ans = ans + chr(int(s[i-2:i])+96)\n i=i-2\n else:\n ans = ans + chr(int(s[i])+96)\n i -= 1\n ... | 29 | There are `n` people and `40` types of hats labeled from `1` to `40`.
Given a 2D integer array `hats`, where `hats[i]` is a list of all hats preferred by the `ith` person.
Return _the number of ways that the `n` people wear different hats to each other_.
Since the answer may be too large, return it modulo `109 + 7`.... | Scan from right to left, in each step of the scanning check whether there is a trailing "#" 2 indexes away. |
Decrypt String from Alphabet to Integer Mapping | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | python 3\n```\nclass Solution:\n def freqAlphabets(self, s: str) -> str:\n out = []\n res=[]\n i= 0 \n while i <len(s)-2: \n if s[i+2] == "#":\n out.append(s[i:i+2]+"#")\n i+=3\n else:\n out.append(s[i])\n i... | 1 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
Decrypt String from Alphabet to Integer Mapping | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | python 3\n```\nclass Solution:\n def freqAlphabets(self, s: str) -> str:\n out = []\n res=[]\n i= 0 \n while i <len(s)-2: \n if s[i+2] == "#":\n out.append(s[i:i+2]+"#")\n i+=3\n else:\n out.append(s[i])\n i... | 1 | There are `n` people and `40` types of hats labeled from `1` to `40`.
Given a 2D integer array `hats`, where `hats[i]` is a list of all hats preferred by the `ith` person.
Return _the number of ways that the `n` people wear different hats to each other_.
Since the answer may be too large, return it modulo `109 + 7`.... | Scan from right to left, in each step of the scanning check whether there is a trailing "#" 2 indexes away. |
Simple explanation with Prefix Sum in Python3 / TypeScript | xor-queries-of-a-subarray | 0 | 1 | # Intuition\nLet\'s briefly explain what the problem is:\n- there\'s a list of `arr`, that has as particular item as an **interval** `[left, right]`\n- our goal is to find **a XOR prefix** from `left` to `right` according to `queries` list \n\nThe first idea we could come up with is to iterate over `queries` and **brut... | 1 | You are given an array `arr` of positive integers. You are also given the array `queries` where `queries[i] = [lefti, righti]`.
For each query `i` compute the **XOR** of elements from `lefti` to `righti` (that is, `arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]` ).
Return an array `answer` where `answer[i]` is... | Simulate the process. Return to refill the container once you meet a plant that needs more water than you have. |
Python3 | Bit Manipulation Trick O(N + M) Time and O(N) Space Solution! | xor-queries-of-a-subarray | 0 | 1 | ```\nclass Solution:\n #Let n = len(arr) and m = len(queries)!\n #Time-Complexity: O(n + m)\n #Space-Complexity: O(n)\n def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:\n #Approach: To get prefix exclusive or from L to R indices, you can first get prefix exclusive\n ... | 0 | You are given an array `arr` of positive integers. You are also given the array `queries` where `queries[i] = [lefti, righti]`.
For each query `i` compute the **XOR** of elements from `lefti` to `righti` (that is, `arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]` ).
Return an array `answer` where `answer[i]` is... | Simulate the process. Return to refill the container once you meet a plant that needs more water than you have. |
Python Solution using Prefix XOR||O(N+Q)|/O(N+Q)||🐍✔ | xor-queries-of-a-subarray | 0 | 1 | \n\n# Complexity\n- Time complexity:\nO(N+Q)\n- Space complexity:\nO(N+Q)\n# Code\n```\nclass Solution:\n def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:\n pxor = [0] * (len(arr)+1)\n n=len(arr)\n for i in range(n):\n pxor[i]=pxor[i-1]^arr[i]#taking prefix... | 1 | You are given an array `arr` of positive integers. You are also given the array `queries` where `queries[i] = [lefti, righti]`.
For each query `i` compute the **XOR** of elements from `lefti` to `righti` (that is, `arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]` ).
Return an array `answer` where `answer[i]` is... | Simulate the process. Return to refill the container once you meet a plant that needs more water than you have. |
Python3 O(N) solution with prefix xor (95.34% Runtime) | xor-queries-of-a-subarray | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nUtilize accumulatd XOR to compute XOR in range [i, j] in constant time\n\n# Approach\n<!-- Describe your approach to solvi... | 0 | You are given an array `arr` of positive integers. You are also given the array `queries` where `queries[i] = [lefti, righti]`.
For each query `i` compute the **XOR** of elements from `lefti` to `righti` (that is, `arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]` ).
Return an array `answer` where `answer[i]` is... | Simulate the process. Return to refill the container once you meet a plant that needs more water than you have. |
SIMPLE PYTHON SOLUTION USING BFS TRAVERSAL | get-watched-videos-by-your-friends | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
SIMPLE PYTHON SOLUTION USING BFS TRAVERSAL | get-watched-videos-by-your-friends | 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 the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
Python 3 || 6 lines, bfs, Counter || T/S: 93% / 78% | get-watched-videos-by-your-friends | 0 | 1 | Here\'s the plan:\n- We keep track of the nodes not visited in our *bfs* with `unseen`.\n- The first `row` in our *bfs* is `id`. We construct each subsequent `row` using the current`row`.\n- We we arrive at the *level*`row`, we use a counter to do the required sort.\n```\nclass Solution:\n def watchedVideosByFriend... | 5 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
Python 3 || 6 lines, bfs, Counter || T/S: 93% / 78% | get-watched-videos-by-your-friends | 0 | 1 | Here\'s the plan:\n- We keep track of the nodes not visited in our *bfs* with `unseen`.\n- The first `row` in our *bfs* is `id`. We construct each subsequent `row` using the current`row`.\n- We we arrive at the *level*`row`, we use a counter to do the required sort.\n```\nclass Solution:\n def watchedVideosByFriend... | 5 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
🤯 [Python] Easy Logic | BFS using Deque + Set + Defaultdict | Codeplug | get-watched-videos-by-your-friends | 0 | 1 | **Upvote if it helped :)**\n\n# Intuition\nWe need to visit the nearest neighbours when we talk about level, this suggests that we should be using BFS with queue.\n\n# Approach\nWe reduce the level as we iterate and when the level is 1, we count all the videos watched by friends at that level using a defaultdict.\n\n# ... | 1 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
🤯 [Python] Easy Logic | BFS using Deque + Set + Defaultdict | Codeplug | get-watched-videos-by-your-friends | 0 | 1 | **Upvote if it helped :)**\n\n# Intuition\nWe need to visit the nearest neighbours when we talk about level, this suggests that we should be using BFS with queue.\n\n# Approach\nWe reduce the level as we iterate and when the level is 1, we count all the videos watched by friends at that level using a defaultdict.\n\n# ... | 1 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
Simple Python3 Solution | Easy to understand | get-watched-videos-by-your-friends | 0 | 1 | # Code\n```\nclass Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n d = deque() # deque for bfs\n videos = [] # videos on searched level\n\n d.appendleft((0, id)) \n visited = {id} # mem visited ... | 0 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
Simple Python3 Solution | Easy to understand | get-watched-videos-by-your-friends | 0 | 1 | # Code\n```\nclass Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n d = deque() # deque for bfs\n videos = [] # videos on searched level\n\n d.appendleft((0, id)) \n visited = {id} # mem visited ... | 0 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
Python | BFS | get-watched-videos-by-your-friends | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n """\n BFS:\n Start with\n - queue containing id\n Perform level (k) times of level order BFS traversals\n At the... | 0 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
Python | BFS | get-watched-videos-by-your-friends | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n """\n BFS:\n Start with\n - queue containing id\n Perform level (k) times of level order BFS traversals\n At the... | 0 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
Python3 Clean BFS Solution | get-watched-videos-by-your-friends | 0 | 1 | \n# Code\n```\nclass Solution:\n def watchedVideosByFriends(self, wv: List[List[str]], fnds: List[List[int]], id: int, level: int) -> List[str]:\n \n \n n=len(wv)\n adj=defaultdict(list)\n \n for i in range(n):\n for x in fnds[i]:\n adj[i].append(x)... | 0 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
Python3 Clean BFS Solution | get-watched-videos-by-your-friends | 0 | 1 | \n# Code\n```\nclass Solution:\n def watchedVideosByFriends(self, wv: List[List[str]], fnds: List[List[int]], id: int, level: int) -> List[str]:\n \n \n n=len(wv)\n adj=defaultdict(list)\n \n for i in range(n):\n for x in fnds[i]:\n adj[i].append(x)... | 0 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
Python - BFS + sorting | get-watched-videos-by-your-friends | 0 | 1 | # Intuition\nThink of this as graph problem where each person is graph node, do the simple BFS and count levels, measure frequency of values on target level. Sort the way it is explained in problem statement.\nI did level start from 1 so I don\'t need to use L+1 in comparisons to children (node to) level!\n\n# Complexi... | 0 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
Python - BFS + sorting | get-watched-videos-by-your-friends | 0 | 1 | # Intuition\nThink of this as graph problem where each person is graph node, do the simple BFS and count levels, measure frequency of values on target level. Sort the way it is explained in problem statement.\nI did level start from 1 so I don\'t need to use L+1 in comparisons to children (node to) level!\n\n# Complexi... | 0 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
Solution | get-watched-videos-by-your-friends | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n\tvector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& friends, int id, int level) \n\t{\n\t\tint size_of_friends = friends.size();\n\t\tint oth_param = -1;\n\t\tint clr_var = 0;\n int ctrl_flag = -1;\n\n\t\tvector<string> my_v1;\n\t\... | 0 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
Solution | get-watched-videos-by-your-friends | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n\tvector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& friends, int id, int level) \n\t{\n\t\tint size_of_friends = friends.size();\n\t\tint oth_param = -1;\n\t\tint clr_var = 0;\n int ctrl_flag = -1;\n\n\t\tvector<string> my_v1;\n\t\... | 0 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
Python3 - BFS + Hash Table | get-watched-videos-by-your-friends | 0 | 1 | # Code\n```\nfrom collections import Counter\nclass Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n graph, visited, dist = {}, [], []\n n, mx = len(watchedVideos), float("inf")\n\n for i in range(n):\n ... | 0 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
Python3 - BFS + Hash Table | get-watched-videos-by-your-friends | 0 | 1 | # Code\n```\nfrom collections import Counter\nclass Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n graph, visited, dist = {}, [], []\n n, mx = len(watchedVideos), float("inf")\n\n for i in range(n):\n ... | 0 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
BFS & Hashmap | get-watched-videos-by-your-friends | 0 | 1 | # Approach\nFind level level of friends by BFS.\nThen count the occurences of each movie.\nSort by frequency then name.\n\n# Code\n```\nclass Solution:\n def watchedVideosByFriends(self, w: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n S = {id}\n q = [id]\n\n fo... | 0 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
BFS & Hashmap | get-watched-videos-by-your-friends | 0 | 1 | # Approach\nFind level level of friends by BFS.\nThen count the occurences of each movie.\nSort by frequency then name.\n\n# Code\n```\nclass Solution:\n def watchedVideosByFriends(self, w: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n S = {id}\n q = [id]\n\n fo... | 0 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
Simple to understand Python code with comments and explanation. | get-watched-videos-by-your-friends | 0 | 1 | \n# Code\n```python\nclass Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n #Here is what I think:\n # - Find all friends in level k\n # - Count the frequency of each video\n # - Sort the v... | 0 | There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`.
Level **1** of videos are all watched videos by your... | Check all squares in the matrix and find the largest one. |
Simple to understand Python code with comments and explanation. | get-watched-videos-by-your-friends | 0 | 1 | \n# Code\n```python\nclass Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n #Here is what I think:\n # - Find all friends in level k\n # - Count the frequency of each video\n # - Sort the v... | 0 | You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil... | Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly. |
Python3 clean Solution beats 💯 100% with Proof 🔥 | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # Code\n```\nclass Solution:\n def minInsertions(self, s: str) -> int:\n if s == s[::-1]: return 0 \n n = len(s)\n dp = [[0] * n for _ in range(n)]\n for i in range(n-1,-1,-1):\n dp[i][i] = 1\n for j in range(i+1,n):\n if s[i] == s[j]:dp[i][j] = dp[i+1... | 3 | Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zz... | Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array. |
Python3 clean Solution beats 💯 100% with Proof 🔥 | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # Code\n```\nclass Solution:\n def minInsertions(self, s: str) -> int:\n if s == s[::-1]: return 0 \n n = len(s)\n dp = [[0] * n for _ in range(n)]\n for i in range(n-1,-1,-1):\n dp[i][i] = 1\n for j in range(i+1,n):\n if s[i] == s[j]:dp[i][j] = dp[i+1... | 3 | Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example ... | Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome. |
[ Python ] ✅✅ Simple Python Solution Using Dynamic Programming🥳✌👍 | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 1317 ms, faster than 27.39% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome.\n# Memory Usage: 16 MB, less than 67.55% of Python3 online submissions for Minimum Insertion Step... | 1 | Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zz... | Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array. |
[ Python ] ✅✅ Simple Python Solution Using Dynamic Programming🥳✌👍 | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 1317 ms, faster than 27.39% of Python3 online submissions for Minimum Insertion Steps to Make a String Palindrome.\n# Memory Usage: 16 MB, less than 67.55% of Python3 online submissions for Minimum Insertion Step... | 1 | Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example ... | Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome. |
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++ | minimum-insertion-steps-to-make-a-string-palindrome | 1 | 1 | # My youtube channel - KeetCode(Ex-Amazon)\nI create 155 videos for leetcode questions as of April 24, 2023. I believe my channel helps you prepare for the coming technical interviews. Please subscribe my channel!\n\n### Please subscribe my channel - KeetCode(Ex-Amazon) from here.\n\n**I created a video for this questi... | 1 | Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zz... | Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array. |
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++ | minimum-insertion-steps-to-make-a-string-palindrome | 1 | 1 | # My youtube channel - KeetCode(Ex-Amazon)\nI create 155 videos for leetcode questions as of April 24, 2023. I believe my channel helps you prepare for the coming technical interviews. Please subscribe my channel!\n\n### Please subscribe my channel - KeetCode(Ex-Amazon) from here.\n\n**I created a video for this questi... | 1 | Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example ... | Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome. |
Short simple python solution using DP | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # Code\n```\nclass Solution:\n def minInsertions(self, s: str) -> int:\n dp=[[-1]*501 for _ in range(501)]\n def dfs(i,j):\n if i>j or i==j:\n return 0\n if dp[i][j]!=-1:\n return dp[i][j]\n if s[i]==s[j]:\n dp[i][j]=dfs(i+1,... | 1 | Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zz... | Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array. |
Short simple python solution using DP | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # Code\n```\nclass Solution:\n def minInsertions(self, s: str) -> int:\n dp=[[-1]*501 for _ in range(501)]\n def dfs(i,j):\n if i>j or i==j:\n return 0\n if dp[i][j]!=-1:\n return dp[i][j]\n if s[i]==s[j]:\n dp[i][j]=dfs(i+1,... | 1 | Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example ... | Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome. |
python 3 - top down dp | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # Intuition\nLogic is straightforward.\n\nstate variable = left, right\nDo all combination of left and right -> DP should be used.\nIf s[left] == s[right], skip both left and right. Else, add either s[left] or s[right] and repeat the process.\n\n# Approach\ntop-down dp\n\n# Complexity\n- Time complexity:\nO(n^2) -> dp ... | 1 | Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zz... | Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array. |
python 3 - top down dp | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # Intuition\nLogic is straightforward.\n\nstate variable = left, right\nDo all combination of left and right -> DP should be used.\nIf s[left] == s[right], skip both left and right. Else, add either s[left] or s[right] and repeat the process.\n\n# Approach\ntop-down dp\n\n# Complexity\n- Time complexity:\nO(n^2) -> dp ... | 1 | Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example ... | Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome. |
Python Top Down Memoization Solution | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | ```\neg: leetcode \nWe try to insert at both ends if not equal\n\n1. Insert to the right and match \'l\', cost is 1 then check remaining string : 1 + rec(i+1,j)\n2. Insert to left and match \'e\' , cost is 1 then check the remaining string : 1+rec(i,j-1)\n3. if the ends are the same character , no cost : rec(i+1,j) \... | 1 | Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zz... | Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array. |
Python Top Down Memoization Solution | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | ```\neg: leetcode \nWe try to insert at both ends if not equal\n\n1. Insert to the right and match \'l\', cost is 1 then check remaining string : 1 + rec(i+1,j)\n2. Insert to left and match \'e\' , cost is 1 then check the remaining string : 1+rec(i,j-1)\n3. if the ends are the same character , no cost : rec(i+1,j) \... | 1 | Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example ... | Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome. |
Python easy 7-liner | DP | Top-down & Bottom-up | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # Code\n\n***Top Down***\n```\nclass Solution:\n def minInsertions(self, s: str) -> int:\n @lru_cache(None)\n def dp(i, j):\n if i >= j:\n return 0\n\n if s[i] == s[j]:\n return dp(i+1, j-1)\n else:\n return 1+min(dp(i+1, j),... | 1 | Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zz... | Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array. |
Python easy 7-liner | DP | Top-down & Bottom-up | minimum-insertion-steps-to-make-a-string-palindrome | 0 | 1 | # Code\n\n***Top Down***\n```\nclass Solution:\n def minInsertions(self, s: str) -> int:\n @lru_cache(None)\n def dp(i, j):\n if i >= j:\n return 0\n\n if s[i] == s[j]:\n return dp(i+1, j-1)\n else:\n return 1+min(dp(i+1, j),... | 1 | Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example ... | Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome. |
Easy Python Solution || Let's Decompress Run-Length Encoded List....... | decompress-run-length-encoded-list | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves decompressing a run-length encoded list. Run-length encoding represents consecutive elements with the same value as a single pair of value and frequency. The goal is to reconstruct the original list.\n# Approach\n<!--... | 3 | 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 😎😀😎 || Faster than 97.88% & Memory beats 98.41% | decompress-run-length-encoded-list | 0 | 1 | Plz upvote if you find this helpful and I\'ll upvote your comment or your posts! : )\n# Code\n```\nclass Solution:\n def decompressRLElist(self, nums: List[int]) -> List[int]:\n generated = [] # just a starter array\n for i in range(0, len(nums), 2): # skip by 2 because...\n freq = nums[i]... | 14 | 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... |
Decompress run length encoded list | decompress-run-length-encoded-list | 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 | 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 Solution | Beginners Friendly | Explained | decompress-run-length-encoded-list | 0 | 1 | 1. Create an empty list `res`.\n2. Iterate in the Range of floor division of length of the `nums` by `2` (`range(len(nums)//2)`)\n3. Create two variables and assign them the values of `nums[2*i]` and `nums[(2*i)+1` respectively\n4. Iterate again in the range of `freq + 1`.\n5. At last Condition the value in the loop t... | 6 | 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/JS/Go/C++ O( m*n ) Integral Image // DP [ w/ Explanation ] | matrix-block-sum | 0 | 1 | O( m*n ) sol. based on integral image technique ( 2D DP ).\n\n---\n\n**Explanation on integral image**:\n\nHere we use the technique of **integral image**, which is introduced to **speed up block computation**.\n\nAlso, this technique is practical and common in the field of matrix operation and image processing such as... | 165 | Given a `m x n` matrix `mat` and an integer `k`, return _a matrix_ `answer` _where each_ `answer[i][j]` _is the sum of all elements_ `mat[r][c]` _for_:
* `i - k <= r <= i + k,`
* `j - k <= c <= j + k`, and
* `(r, c)` is a valid position in the matrix.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8... | null |
Python, Two Approaches: Easy-to-understand w Explanation | matrix-block-sum | 0 | 1 | ### Approach 1: Brute Force\n\nThis is by far the simplest and shortest solution. How it works:\n\n- Loop through each ```(x, y)``` coordinate in the resultant array ```result```.\n- At each ```result[x][y]```, get the appropriate subarray from the matrix ```mat```. I.e., for each ```(x, y)``` in ```result```, get the ... | 12 | Given a `m x n` matrix `mat` and an integer `k`, return _a matrix_ `answer` _where each_ `answer[i][j]` _is the sum of all elements_ `mat[r][c]` _for_:
* `i - k <= r <= i + k,`
* `j - k <= c <= j + k`, and
* `(r, c)` is a valid position in the matrix.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8... | null |
Python3 || Beats 99.61% || DFS | sum-of-nodes-with-even-valued-grandparent | 0 | 1 | \n# Please UPVOTE\uD83D\uDE0A\n\n# Python3\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.le... | 20 | Given the `root` of a binary tree, return _the sum of values of nodes with an **even-valued grandparent**_. If there are no nodes with an **even-valued grandparent**, return `0`.
A **grandparent** of a node is the parent of its parent if it exists.
**Example 1:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,nul... | null |
✔💖Easiest Solution in Python || Step by step explanation | sum-of-nodes-with-even-valued-grandparent | 0 | 1 | # Approach\n**Step 1:** Create a variable **sum** which will store the sum of all the nodes which are having their grandparents wih even value.\n\n**Step 2:** Check if the root node their is their, if it is then move ahead else return 0.\n\n**Step 3:** Now check if the current node value is even, and if it is even then... | 3 | Given the `root` of a binary tree, return _the sum of values of nodes with an **even-valued grandparent**_. If there are no nodes with an **even-valued grandparent**, return `0`.
A **grandparent** of a node is the parent of its parent if it exists.
**Example 1:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,nul... | null |
Recursive | Time Complexity - O(N) | sum-of-nodes-with-even-valued-grandparent | 0 | 1 | Please upvote if you like the solution .\n\n```\nclass Solution:\n def sumEvenGrandparent(self, root: TreeNode) -> int:\n def helper(grandparent, parent, node):\n if not node:return\n if grandparent and grandparent.val%2 == 0:self.ans += node.val\n helper(parent, node, node.le... | 2 | Given the `root` of a binary tree, return _the sum of values of nodes with an **even-valued grandparent**_. If there are no nodes with an **even-valued grandparent**, return `0`.
A **grandparent** of a node is the parent of its parent if it exists.
**Example 1:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,nul... | null |
✅ 🔥 Python3 || ⚡easy solution | distinct-echo-substrings | 0 | 1 | ```\nclass Solution:\n def distinctEchoSubstrings(self, text: str) -> int:\n text_values = [ord(char) - 97 for char in text]\n hash_map = {}\n powers_of_26 = [1]\n \n\n for i in range(1, len(text) + 1):\n powers_of_26.append(powers_of_26[i - 1] * 26)\n \n\n ... | 0 | You have the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, "Fizz", 4, "Buzz", ...] where the ith token (1-indexed) of the... | null |
Simple Python Code (1231ms) | distinct-echo-substrings | 0 | 1 | # Approach\n\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\nbeats ~ 70%\n\n- Space complexity:\n$$O(n)$$\nbeats ~ 31%\n\n# Code\n```\nimport math\nclass Solution:\n def distinctEchoSubstrings(self, text) :\n n = len(text)\n m = 0\n max_n = math.floor(n/2)\n substrs = set()\n for ... | 0 | You have the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, "Fizz", 4, "Buzz", ...] where the ith token (1-indexed) of the... | null |
Python3 rolling hash O(n^2) Python3 | distinct-echo-substrings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# 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 the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, "Fizz", 4, "Buzz", ...] where the ith token (1-indexed) of the... | null |
My attempt towards an O(n) solution | distinct-echo-substrings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhenever there exists a substring that meets the condition, the leading char in the second half must have been seen previously.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAs we traverse the text char by char, ... | 0 | You have the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, "Fizz", 4, "Buzz", ...] where the ith token (1-indexed) of the... | null |
Solution | distinct-echo-substrings | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int distinctEchoSubstrings(string text) {\n unordered_set<string> result;\n int l = text.length() - 1;\n for (int i = 0; i < l; ++i) {\n const auto& substr_len = KMP(text, i, &result);\n if (substr_len != numeric_limits<int>::max()) {... | 0 | You have the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, "Fizz", 4, "Buzz", ...] where the ith token (1-indexed) of the... | null |
Fast | Python Solution | distinct-echo-substrings | 0 | 1 | # Code\n```\nclass Solution:\n def distinctEchoSubstrings(self, text: str) -> int:\n n = len(text)\n\t\t\n def helper(size):\n base = 1 << 5\n M = 10 ** 9 + 7\n a = pow(base, size, M)\n t = 0\n vis = defaultdict(set)\n vis_pattern = set(... | 0 | You have the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, "Fizz", 4, "Buzz", ...] where the ith token (1-indexed) of the... | null |
Python - O(N^2) - easy to understand | distinct-echo-substrings | 0 | 1 | # Approach\necho substring is a + a. so for each text[i] for i from 0 -> len(text) -1 and for j from i -> len(text). get prefix = text[i: j + 1], suffix = text[j + 1: j + 1 + len(prefix)]. if prefix == suffix: ans.add(prefix)\n\nthen return len(ans)\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n)... | 0 | You have the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, "Fizz", 4, "Buzz", ...] where the ith token (1-indexed) of the... | null |
[Python] Solution | distinct-echo-substrings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# 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 the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, "Fizz", 4, "Buzz", ...] where the ith token (1-indexed) of the... | null |
Python Hashing + Memo Solution | Easy to Understand | Faster than 60% | distinct-echo-substrings | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n```dp[start][end]``` contains the hashing value of substring ```text[start: end + 1]```\n\nIf ```text[start: start + substrLen]``` is equal to ```text[start + substrLen: start + substrLen * 2]```, we will have ```dp[start][start + substrLen-1] == dp[s... | 0 | You have the four functions: You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Modify the given class to output the series [1, 2, "Fizz", 4, "Buzz", ...] where the ith token (1-indexed) of the... | null |
Simple Python solution | convert-integer-to-the-sum-of-two-no-zero-integers | 0 | 1 | \n# Code\n```\nclass Solution:\n def nz(self, num):\n return not str(num).count(\'0\')\n def getNoZeroIntegers(self, n: int) -> List[int]:\n for i in range(1, n):\n if self.nz(i) and self.nz(n-i):\n return [i, n-i]\n``` | 2 | **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation.
Given an integer `n`, return _a list of two integers_ `[a, b]` _where_:
* `a` and `b` are **No-Zero integers**.
* `a + b = n`
The test cases are generated so that there is at least one valid solution. If th... | null |
91.52% 25ms Python3 One-liner and detailed version | convert-integer-to-the-sum-of-two-no-zero-integers | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def getNoZeroIntegers(self, n: int) -> List[int]:\n for i in range(n-1, -1, -1):\n if \'0\' not in str(i) and \'0\' not in str(n - i):\n return [i, n-i ]\n\n #Oneliner\n\n return next([i, n-i] for i in range(n-1, -1, -1) if \'0\' not i... | 1 | **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation.
Given an integer `n`, return _a list of two integers_ `[a, b]` _where_:
* `a` and `b` are **No-Zero integers**.
* `a + b = n`
The test cases are generated so that there is at least one valid solution. If th... | null |
Python Easy Solution Faster Than 98.86% | convert-integer-to-the-sum-of-two-no-zero-integers | 0 | 1 | ```\nclass Solution:\n def getNoZeroIntegers(self, n: int) -> List[int]:\n def check(num):\n while num>0:\n if num%10==0:\n return False\n num//=10\n return True\n for i in range(1,n):\n t=n-i\n if check(t) and... | 2 | **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation.
Given an integer `n`, return _a list of two integers_ `[a, b]` _where_:
* `a` and `b` are **No-Zero integers**.
* `a + b = n`
The test cases are generated so that there is at least one valid solution. If th... | null |
convert-integer-to-the-sum-of-two-no-zero-integers | convert-integer-to-the-sum-of-two-no-zero-integers | 0 | 1 | # Code\n```\nclass Solution:\n def getNoZeroIntegers(self, n: int) -> List[int]:\n for i in range(n-1,-1,-1):\n if str(i).count("0")==0 and str(n-i).count("0")==0:\n return [i,n-i]\n\n \n``` | 0 | **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation.
Given an integer `n`, return _a list of two integers_ `[a, b]` _where_:
* `a` and `b` are **No-Zero integers**.
* `a + b = n`
The test cases are generated so that there is at least one valid solution. If th... | null |
easy cod python | convert-integer-to-the-sum-of-two-no-zero-integers | 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 | **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation.
Given an integer `n`, return _a list of two integers_ `[a, b]` _where_:
* `a` and `b` are **No-Zero integers**.
* `a + b = n`
The test cases are generated so that there is at least one valid solution. If th... | null |
easy 5 line solution | convert-integer-to-the-sum-of-two-no-zero-integers | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nsince we need a no-zero integer eliminate all numbers having 0 in decimal representation from 1 to (n-1) and simply use 2 nested for loops to find a & b\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n> find all nu... | 0 | **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation.
Given an integer `n`, return _a list of two integers_ `[a, b]` _where_:
* `a` and `b` are **No-Zero integers**.
* `a + b = n`
The test cases are generated so that there is at least one valid solution. If th... | null |
Python. Finding zero in a string | convert-integer-to-the-sum-of-two-no-zero-integers | 0 | 1 | In the for loop we only work with half the numbers (`n//2+1`). Although in fact you only need 112 (`range(1, 113)`) - I counted \uD83D\uDE00\n\nCasting a number to a string and searching for the zero character in it turned out to be faster than checking the remainder of division by 10\n\n# Code\n```\nclass Solution:\n ... | 0 | **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation.
Given an integer `n`, return _a list of two integers_ `[a, b]` _where_:
* `a` and `b` are **No-Zero integers**.
* `a + b = n`
The test cases are generated so that there is at least one valid solution. If th... | null |
Simple Python3: Beats 91% solutions, 3 lines code | convert-integer-to-the-sum-of-two-no-zero-integers | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Convert potential integers to strings and check if they contain \'0\'\n2. If not, then return the first instance\n\n# Code\n```\nclass Solution:\n def getNoZeroIntegers(self, n: int) -> List[int]:\n for i in range(1, n):\n if s... | 0 | **No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation.
Given an integer `n`, return _a list of two integers_ `[a, b]` _where_:
* `a` and `b` are **No-Zero integers**.
* `a + b = n`
The test cases are generated so that there is at least one valid solution. If th... | null |
Odd_Even.py | minimum-flips-to-make-a-or-b-equal-to-c | 0 | 1 | # Code\n```\nclass Solution:\n def minFlips(self, a: int, b: int, c: int) -> int:\n ans=0\n while a or b or c:\n x,y,z=a%2,b%2,c%2\n print(x,y,z)\n if z==0:ans+=(x+y)\n elif x==0 and y==0:ans+=1\n a,b,c=a//2,b//2,c//2\n return ans\n```\n\n![... | 4 | Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation).
Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
**Example 1:**
**Input:** a = 2, b = 6... | null |
Odd_Even.py | minimum-flips-to-make-a-or-b-equal-to-c | 0 | 1 | # Code\n```\nclass Solution:\n def minFlips(self, a: int, b: int, c: int) -> int:\n ans=0\n while a or b or c:\n x,y,z=a%2,b%2,c%2\n print(x,y,z)\n if z==0:ans+=(x+y)\n elif x==0 and y==0:ans+=1\n a,b,c=a//2,b//2,c//2\n return ans\n```\n\n![... | 4 | You are given an integer array `target` and an integer `n`.
You have an empty stack with the two following operations:
* **`"Push "`**: pushes an integer to the top of the stack.
* **`"Pop "`**: removes the integer on the top of the stack.
You also have a stream of the integers in the range `[1, n]`.
Use the tw... | Check the bits one by one whether they need to be flipped. |
Python solution | minimum-flips-to-make-a-or-b-equal-to-c | 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 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation).
Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
**Example 1:**
**Input:** a = 2, b = 6... | null |
Python solution | minimum-flips-to-make-a-or-b-equal-to-c | 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 array `target` and an integer `n`.
You have an empty stack with the two following operations:
* **`"Push "`**: pushes an integer to the top of the stack.
* **`"Pop "`**: removes the integer on the top of the stack.
You also have a stream of the integers in the range `[1, n]`.
Use the tw... | Check the bits one by one whether they need to be flipped. |
[Python] Simple and intuitive bit manipulation 🤙 | 1 line | minimum-flips-to-make-a-or-b-equal-to-c | 0 | 1 | # Intuition\n\n\nThere are only three scenarios that require flipping.\n\n- c == 1\n - if a == 0 and b == 0: flip a or b to 1\n- c == 0\n - if a == 1: flip a to 0\n - if b == 1: flip b to 0\... | 1 | Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation).
Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
**Example 1:**
**Input:** a = 2, b = 6... | null |
[Python] Simple and intuitive bit manipulation 🤙 | 1 line | minimum-flips-to-make-a-or-b-equal-to-c | 0 | 1 | # Intuition\n\n\nThere are only three scenarios that require flipping.\n\n- c == 1\n - if a == 0 and b == 0: flip a or b to 1\n- c == 0\n - if a == 1: flip a to 0\n - if b == 1: flip b to 0\... | 1 | You are given an integer array `target` and an integer `n`.
You have an empty stack with the two following operations:
* **`"Push "`**: pushes an integer to the top of the stack.
* **`"Pop "`**: removes the integer on the top of the stack.
You also have a stream of the integers in the range `[1, n]`.
Use the tw... | Check the bits one by one whether they need to be flipped. |
Java+ Python Solution || comparing the Each bit of the binary number | minimum-flips-to-make-a-or-b-equal-to-c | 1 | 1 | # Approach\nFirst converted all three numbers from decimal to binary and padded the elements which are less in length than binary number of max length among three, After converting checking the each bit of a , b with c based on that we will get the minimum number of changes. \n# Complexity\n- Time complexity:\nO(n)\n\... | 1 | Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation).
Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
**Example 1:**
**Input:** a = 2, b = 6... | null |
Java+ Python Solution || comparing the Each bit of the binary number | minimum-flips-to-make-a-or-b-equal-to-c | 1 | 1 | # Approach\nFirst converted all three numbers from decimal to binary and padded the elements which are less in length than binary number of max length among three, After converting checking the each bit of a , b with c based on that we will get the minimum number of changes. \n# Complexity\n- Time complexity:\nO(n)\n\... | 1 | You are given an integer array `target` and an integer `n`.
You have an empty stack with the two following operations:
* **`"Push "`**: pushes an integer to the top of the stack.
* **`"Pop "`**: removes the integer on the top of the stack.
You also have a stream of the integers in the range `[1, n]`.
Use the tw... | Check the bits one by one whether they need to be flipped. |
Python3 Solution || DFS Approach | number-of-operations-to-make-network-connected | 0 | 1 | # Complexity\n- Time complexity:\nO(E+V)\n\n- Space complexity:\nO(V)\n\n# Code\n```\nclass Solution:\n def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n adj=defaultdict(list)\n for ele1,ele2 in connections:\n adj[ele1].append(ele2)\n adj[ele2].append(ele1)\n... | 2 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
Python3 Solution || DFS Approach | number-of-operations-to-make-network-connected | 0 | 1 | # Complexity\n- Time complexity:\nO(E+V)\n\n- Space complexity:\nO(V)\n\n# Code\n```\nclass Solution:\n def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n adj=defaultdict(list)\n for ele1,ele2 in connections:\n adj[ele1].append(ele2)\n adj[ele2].append(ele1)\n... | 2 | Given an array of integers `arr`.
We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`.
Let's define `a` and `b` as follows:
* `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]`
* `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]`
Note that **^** denotes the **bitwise-xor** operation.
Return... | As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters. |
Python union find solution | number-of-operations-to-make-network-connected | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse Union find to count the redundant connections and connected clusters.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlog(n))\n<!-- Add your time complexity here, e.g. $$O(... | 5 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
Python union find solution | number-of-operations-to-make-network-connected | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse Union find to count the redundant connections and connected clusters.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlog(n))\n<!-- Add your time complexity here, e.g. $$O(... | 5 | Given an array of integers `arr`.
We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`.
Let's define `a` and `b` as follows:
* `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]`
* `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]`
Note that **^** denotes the **bitwise-xor** operation.
Return... | As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters. |
Simple solution with using Depth-First Search in Python3 | number-of-operations-to-make-network-connected | 0 | 1 | # Intuition\nThe problem description is the following:\n- there\'s an **undirected graph** with `n` nodes and `connections` edges\n- our goal is to find **the minimum amount of connections we should switch** in order to make all the network **connected**\n\n**PS: there\'re at least two valid solutions.** The first one ... | 1 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
Simple solution with using Depth-First Search in Python3 | number-of-operations-to-make-network-connected | 0 | 1 | # Intuition\nThe problem description is the following:\n- there\'s an **undirected graph** with `n` nodes and `connections` edges\n- our goal is to find **the minimum amount of connections we should switch** in order to make all the network **connected**\n\n**PS: there\'re at least two valid solutions.** The first one ... | 1 | Given an array of integers `arr`.
We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`.
Let's define `a` and `b` as follows:
* `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]`
* `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]`
Note that **^** denotes the **bitwise-xor** operation.
Return... | As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters. |
Python Readable - Simple Intuition | number-of-operations-to-make-network-connected | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Scope the problem -> Find the min moves needed to connect all nodes.\n2. What kind of problem is this? Graph Problem. Think DFS BFS Union-Find.\n3. How to connect node? Remove 1 wire and use it on another\n3. How do I know if its unsol... | 1 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
Python Readable - Simple Intuition | number-of-operations-to-make-network-connected | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Scope the problem -> Find the min moves needed to connect all nodes.\n2. What kind of problem is this? Graph Problem. Think DFS BFS Union-Find.\n3. How to connect node? Remove 1 wire and use it on another\n3. How do I know if its unsol... | 1 | Given an array of integers `arr`.
We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`.
Let's define `a` and `b` as follows:
* `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]`
* `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]`
Note that **^** denotes the **bitwise-xor** operation.
Return... | As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters. |
Python Solution O(E) | Adj List + BFS/DFS + Connected Components | number-of-operations-to-make-network-connected | 0 | 1 | 1. Using BFS\n```\ndef makeConnected(self, n: int, connections: List[List[int]]) -> int:\n #check if possible , should have atleast n-1 edges\n if(len(connections) < n-1 ):\n return -1 \n\n #build adjacency list, bidirectional edges\n graph = { i:[] for i in range(0,n)}\n for item in connections:\... | 1 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
Python Solution O(E) | Adj List + BFS/DFS + Connected Components | number-of-operations-to-make-network-connected | 0 | 1 | 1. Using BFS\n```\ndef makeConnected(self, n: int, connections: List[List[int]]) -> int:\n #check if possible , should have atleast n-1 edges\n if(len(connections) < n-1 ):\n return -1 \n\n #build adjacency list, bidirectional edges\n graph = { i:[] for i in range(0,n)}\n for item in connections:\... | 1 | Given an array of integers `arr`.
We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`.
Let's define `a` and `b` as follows:
* `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]`
* `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]`
Note that **^** denotes the **bitwise-xor** operation.
Return... | As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters. |
Python3 Solution | number-of-operations-to-make-network-connected | 0 | 1 | \n```\nclass Solution:\n def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n parent=list(range(n))\n self.count=n\n self.redundant=0\n def find(x):\n if x!=parent[x]:\n parent[x]=find(parent[x])\n\n return parent[x]\n\n def u... | 1 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
Python3 Solution | number-of-operations-to-make-network-connected | 0 | 1 | \n```\nclass Solution:\n def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n parent=list(range(n))\n self.count=n\n self.redundant=0\n def find(x):\n if x!=parent[x]:\n parent[x]=find(parent[x])\n\n return parent[x]\n\n def u... | 1 | Given an array of integers `arr`.
We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`.
Let's define `a` and `b` as follows:
* `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]`
* `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]`
Note that **^** denotes the **bitwise-xor** operation.
Return... | As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters. |
Simple 🐍python solution using DFS ✔ | number-of-operations-to-make-network-connected | 0 | 1 | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nConnected components concept in graph theory.\n\n\n# Code\n```\nclass Solution:\n def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n graph = {}\n\n for i in range(n):\n graph[i] = []\n \n ... | 1 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
Simple 🐍python solution using DFS ✔ | number-of-operations-to-make-network-connected | 0 | 1 | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nConnected components concept in graph theory.\n\n\n# Code\n```\nclass Solution:\n def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n graph = {}\n\n for i in range(n):\n graph[i] = []\n \n ... | 1 | Given an array of integers `arr`.
We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`.
Let's define `a` and `b` as follows:
* `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]`
* `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]`
Note that **^** denotes the **bitwise-xor** operation.
Return... | As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters. |
Python || Top Down DP | minimum-distance-to-type-a-word-using-two-fingers | 0 | 1 | Assume board as a grid of m*n and store corrdinates of each char in a dictionary.\nuse top down dp and memoize it.\nTime Complexity - O(len(word)*m^2*n^2) where m and n are rows and columns of keyboard\n\n```\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n n=len(word)\n graph={}\n ... | 1 | You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate.
* For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `... | Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character. |
Python || Top Down DP | minimum-distance-to-type-a-word-using-two-fingers | 0 | 1 | Assume board as a grid of m*n and store corrdinates of each char in a dictionary.\nuse top down dp and memoize it.\nTime Complexity - O(len(word)*m^2*n^2) where m and n are rows and columns of keyboard\n\n```\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n n=len(word)\n graph={}\n ... | 1 | Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex.... | Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word. |
SImple DP in python3 | minimum-distance-to-type-a-word-using-two-fingers | 0 | 1 | # Code\n```\nclass Solution:\n def minimumDistance(self, word: str) -> int:\n def place(l):\n a = ord(l) - ord(\'A\')\n return (a//6,a%6)\n places = {a:place(a) for a in \'ABCDEFGHIJKLMNOPQRSTUVWXYZ\'}\n def dist(a,b):\n if a == None:\n return 0\n ... | 0 | You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate.
* For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `... | Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.