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
NOOB CODE : EASY TO UNDERSTAND
goat-latin
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. If a word begins with a vowel (a, e, i, o, u, A, E, I, O, U), append "ma" to the end of the word.\n2. If a word begins with a consonant, remove the first letter and append it to the end of the word, followed by "ma."\n3. For each word, add \'a\' (in increasing order starting with \'a\') to the end of the resulting word.\n\nLet\'s break down the code step by step:\n\n1. `l = sentence.split()`: The input sentence is split into words, and the resulting list of words is stored in the `l` variable.\n\n2. `v = set([\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\'])`: A set `v` is created to hold vowels in both lowercase and uppercase.\n\n3. `str1 = \'\'`: An empty string `str1` is initialized to store the transformed sentence.\n\n4. `r = \'\'`, `at = \'\'`, `st = \'\'`: These variables are initialized for temporary storage within the loop.\n\n5. The code then iterates through each word in the `l` list (representing words in the input sentence):\n\n a. `at = \'a\' * (intr + 1)`: This line calculates the \'a\' sequence based on the word\'s position in the sentence. The \'a\' sequence increases by one with each word.\n\n b. `st = l[intr]`: Retrieves the current word from the list.\n\n c. Checks if the first letter of the word (`st[0]`) is in the set of vowels (`v`). If it is, it means the word starts with a vowel, so:\n - `r = st + \'ma\'`: The word is appended with "ma."\n\n d. If the word doesn\'t start with a vowel (i.e., it starts with a consonant), it performs the following steps:\n - A loop is used to iterate through the characters of the word starting from the second character (`st[1:]`), and they are concatenated to the `r` variable.\n - The first character of the word (`st[0]`) is then added to the end of the `r` variable.\n - Finally, "ma" is appended to the `r` variable.\n\n e. The \'a\' sequence calculated earlier (`at`) is added to the end of the `r` variable.\n\n f. The `r` variable, representing the transformed word, is appended to the `str1` variable with a space.\n\n6. Finally, the code returns `str1[1:]`, which removes the leading space, providing the correctly formatted Goat Latin sentence.\n\n# Complexity\n- Time complexity: ***O(n * m)***\nwhere n is the number of words in the sentence, and m is the average length of a word\n- Space complexity: ***O(n)***\n\n\n# Code\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n l = sentence.split()\n v = set([\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\'])\n str1 = \'\'\n r = \'\'\n at = \'\'\n st = \'\'\n for intr in range(len(l)):\n r = \'\'\n at = \'a\' * (intr + 1)\n st = l[intr]\n if st[0] in v:\n r = st + \'ma\'\n else:\n if len(st) > 1:\n for m in range(1, len(st)):\n r = r + st[m]\n r = r + st[0]\n r = r + \'ma\'\n r = r + at\n str1 = str1 + \' \' + r\n return str1[1:]\n\n```
3
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
NOOB CODE : EASY TO UNDERSTAND
goat-latin
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. If a word begins with a vowel (a, e, i, o, u, A, E, I, O, U), append "ma" to the end of the word.\n2. If a word begins with a consonant, remove the first letter and append it to the end of the word, followed by "ma."\n3. For each word, add \'a\' (in increasing order starting with \'a\') to the end of the resulting word.\n\nLet\'s break down the code step by step:\n\n1. `l = sentence.split()`: The input sentence is split into words, and the resulting list of words is stored in the `l` variable.\n\n2. `v = set([\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\'])`: A set `v` is created to hold vowels in both lowercase and uppercase.\n\n3. `str1 = \'\'`: An empty string `str1` is initialized to store the transformed sentence.\n\n4. `r = \'\'`, `at = \'\'`, `st = \'\'`: These variables are initialized for temporary storage within the loop.\n\n5. The code then iterates through each word in the `l` list (representing words in the input sentence):\n\n a. `at = \'a\' * (intr + 1)`: This line calculates the \'a\' sequence based on the word\'s position in the sentence. The \'a\' sequence increases by one with each word.\n\n b. `st = l[intr]`: Retrieves the current word from the list.\n\n c. Checks if the first letter of the word (`st[0]`) is in the set of vowels (`v`). If it is, it means the word starts with a vowel, so:\n - `r = st + \'ma\'`: The word is appended with "ma."\n\n d. If the word doesn\'t start with a vowel (i.e., it starts with a consonant), it performs the following steps:\n - A loop is used to iterate through the characters of the word starting from the second character (`st[1:]`), and they are concatenated to the `r` variable.\n - The first character of the word (`st[0]`) is then added to the end of the `r` variable.\n - Finally, "ma" is appended to the `r` variable.\n\n e. The \'a\' sequence calculated earlier (`at`) is added to the end of the `r` variable.\n\n f. The `r` variable, representing the transformed word, is appended to the `str1` variable with a space.\n\n6. Finally, the code returns `str1[1:]`, which removes the leading space, providing the correctly formatted Goat Latin sentence.\n\n# Complexity\n- Time complexity: ***O(n * m)***\nwhere n is the number of words in the sentence, and m is the average length of a word\n- Space complexity: ***O(n)***\n\n\n# Code\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n l = sentence.split()\n v = set([\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\'])\n str1 = \'\'\n r = \'\'\n at = \'\'\n st = \'\'\n for intr in range(len(l)):\n r = \'\'\n at = \'a\' * (intr + 1)\n st = l[intr]\n if st[0] in v:\n r = st + \'ma\'\n else:\n if len(st) > 1:\n for m in range(1, len(st)):\n r = r + st[m]\n r = r + st[0]\n r = r + \'ma\'\n r = r + at\n str1 = str1 + \' \' + r\n return str1[1:]\n\n```
3
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
easy
goat-latin
0
1
\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n k = 0\n p = ""\n for x in sentence.split(" "):\n if x[0] not in ("aeiouAEIOU"): \n x = x[1:]+x[0]\n p+=x+"maa"+"a" * k\n k += 1\n if k == len(sentence.split(" ")):\n return p\n p+=" "\n```
1
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
easy
goat-latin
0
1
\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n k = 0\n p = ""\n for x in sentence.split(" "):\n if x[0] not in ("aeiouAEIOU"): \n x = x[1:]+x[0]\n p+=x+"maa"+"a" * k\n k += 1\n if k == len(sentence.split(" ")):\n return p\n p+=" "\n```
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
[Python 3] - Simple Solution w Explanation
goat-latin
0
1
Still fairly new to Python so open to any suggestions or improvements! \n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n new = sentence.split() # Breaks up the input into individual sentences\n count = 1 # Starting at 1 since we only have one "a" to begin with.\n \n for x in range(len(new)):\n if new[x][0].casefold() in \'aeiou\': # Checks if the first value of x is a vowel. The casefold, can be replaced with lower, lowers the case. Can also just be removed and have "in \'aeiouAEIOU\'\n new[x] = new[x] + \'ma\' + \'a\'*count # Brings it together with the count multiplying number of "a"\'s as needed.\n count += 1\n elif new[x].casefold() not in \'aeiou\': # Same comment as above.\n new[x] = new[x][1:] + new[x][0] + \'ma\' + \'a\'*count # Just moves the first value to the end then does the a.\n count += 1\n \n return " ".join(x for x in new) # Converts the list back into a string.\n```\n
4
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
[Python 3] - Simple Solution w Explanation
goat-latin
0
1
Still fairly new to Python so open to any suggestions or improvements! \n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n new = sentence.split() # Breaks up the input into individual sentences\n count = 1 # Starting at 1 since we only have one "a" to begin with.\n \n for x in range(len(new)):\n if new[x][0].casefold() in \'aeiou\': # Checks if the first value of x is a vowel. The casefold, can be replaced with lower, lowers the case. Can also just be removed and have "in \'aeiouAEIOU\'\n new[x] = new[x] + \'ma\' + \'a\'*count # Brings it together with the count multiplying number of "a"\'s as needed.\n count += 1\n elif new[x].casefold() not in \'aeiou\': # Same comment as above.\n new[x] = new[x][1:] + new[x][0] + \'ma\' + \'a\'*count # Just moves the first value to the end then does the a.\n count += 1\n \n return " ".join(x for x in new) # Converts the list back into a string.\n```\n
4
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Python Easy
goat-latin
0
1
\tclass Solution:\n\t\tdef toGoatLatin(self, sentence: str) -> str:\n\t\t\tlst = sentence.split(" ")\n\n\t\t\tlst2 = []\n\n\t\t\tvowels = ["a", "e", "i", "o", "u"]\n\n\t\t\tfor i, word in enumerate(lst):\n\t\t\t\ttmp = word\n\n\t\t\t\tif (word[0].lower() in vowels):\n\t\t\t\t\ttmp = tmp + "ma"\n\n\t\t\t\telse: \n\t\t\t\t\ttmp2 = tmp[1:] + tmp[0] + "ma" \n\t\t\t\t\ttmp = tmp2\n\n\t\t\t\ttmp = tmp + ("a" * (i + 1))\n\n\t\t\t\tlst2.append(tmp)\n\n\t\t\tsentence_latin = " ".join(lst2)\n\n\t\t\treturn sentence_latin\n\n\n
2
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
Python Easy
goat-latin
0
1
\tclass Solution:\n\t\tdef toGoatLatin(self, sentence: str) -> str:\n\t\t\tlst = sentence.split(" ")\n\n\t\t\tlst2 = []\n\n\t\t\tvowels = ["a", "e", "i", "o", "u"]\n\n\t\t\tfor i, word in enumerate(lst):\n\t\t\t\ttmp = word\n\n\t\t\t\tif (word[0].lower() in vowels):\n\t\t\t\t\ttmp = tmp + "ma"\n\n\t\t\t\telse: \n\t\t\t\t\ttmp2 = tmp[1:] + tmp[0] + "ma" \n\t\t\t\t\ttmp = tmp2\n\n\t\t\t\ttmp = tmp + ("a" * (i + 1))\n\n\t\t\t\tlst2.append(tmp)\n\n\t\t\tsentence_latin = " ".join(lst2)\n\n\t\t\treturn sentence_latin\n\n\n
2
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
[Python] (Very Easy to understand solution)
goat-latin
0
1
```\nclass Solution:\n def toGoatLatin(self, S: str) -> str:\n temp = []\n ans = " " # Here space must be present. (So, after joining the words, they wil be separated by space)\n i = 1\n vowel = [\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\']\n for word in S.split(" "):\n if word[0] in vowel:\n word = word + "ma"\n else:\n word = word[1:] + word[0] + "ma"\n word = word + "a"*i\n i = i + 1\n temp.append(word)\n\t\t# Joins all the list elements.\n return ans.join(temp)\n \n```\nIf you have any doubts, head over the **comment** section.\nIf you like this solution, do **UPVOTE**.\nHappy Coding :)
15
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
[Python] (Very Easy to understand solution)
goat-latin
0
1
```\nclass Solution:\n def toGoatLatin(self, S: str) -> str:\n temp = []\n ans = " " # Here space must be present. (So, after joining the words, they wil be separated by space)\n i = 1\n vowel = [\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\']\n for word in S.split(" "):\n if word[0] in vowel:\n word = word + "ma"\n else:\n word = word[1:] + word[0] + "ma"\n word = word + "a"*i\n i = i + 1\n temp.append(word)\n\t\t# Joins all the list elements.\n return ans.join(temp)\n \n```\nIf you have any doubts, head over the **comment** section.\nIf you like this solution, do **UPVOTE**.\nHappy Coding :)
15
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Python3 O(m+n)? or O(m*n) # Runtime: 42ms 61.69% Memory: 13.9mb 63.09%
goat-latin
0
1
```\nvowels = {\'a\', \'e\',\'i\',\'o\',\'u\', \'A\',\'E\',\'I\',\'O\',\'U\'}\n\nclass Solution:\n# O(m+n)?\n# Runtime: 33ms 89.10% Memory: 13.9mb 63.09%\n def toGoatLatin(self, string: str) -> str:\n sub = "maa"\n newString = string.split()\n\n for idx, val in enumerate(newString):\n if val[0] in vowels:\n newString[idx] = newString[idx] + sub + (\'a\' * idx)\n else:\n newString[idx] = newString[idx][1:] + newString[idx][0] + sub + (\'a\' * idx)\n \n\t\treturn \' \'.join(newString)\n```
1
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
Python3 O(m+n)? or O(m*n) # Runtime: 42ms 61.69% Memory: 13.9mb 63.09%
goat-latin
0
1
```\nvowels = {\'a\', \'e\',\'i\',\'o\',\'u\', \'A\',\'E\',\'I\',\'O\',\'U\'}\n\nclass Solution:\n# O(m+n)?\n# Runtime: 33ms 89.10% Memory: 13.9mb 63.09%\n def toGoatLatin(self, string: str) -> str:\n sub = "maa"\n newString = string.split()\n\n for idx, val in enumerate(newString):\n if val[0] in vowels:\n newString[idx] = newString[idx] + sub + (\'a\' * idx)\n else:\n newString[idx] = newString[idx][1:] + newString[idx][0] + sub + (\'a\' * idx)\n \n\t\treturn \' \'.join(newString)\n```
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Simple python solution
goat-latin
0
1
Runtime: 28 ms\nMemory Usage: 14 MB\n\nCreate a list to store vowels and split the sentence into list. Then iterate through the list of sentence and check if first letter is vowel or consonant. If it is consonant then store the first letter in a variable and and remove that letter using slicing after that add that letter at the end of the word. Finally add "ma" and "a" accordingly.\nAny suggestions or feedbacks are welcome.\n\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n vwl_lst = [\'a\',\'e\',\'i\',\'o\',\'u\',\'A\',\'E\',\'I\',\'O\',\'U\']\n \n sentence = sentence.split()\n \n for i in range(len(sentence)):\n if sentence[i][0] in vwl_lst:\n \n sentence[i] = sentence[i]+"ma"+ ("a"*(i+1))\n else:\n a = sentence[i][0]\n sentence[i] = sentence[i][1:]\n sentence[i] = sentence[i]+a\n sentence[i] = sentence[i]+"ma"+("a"*(i+1))\n \n return \' \'.join(sentence)\n```
1
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
Simple python solution
goat-latin
0
1
Runtime: 28 ms\nMemory Usage: 14 MB\n\nCreate a list to store vowels and split the sentence into list. Then iterate through the list of sentence and check if first letter is vowel or consonant. If it is consonant then store the first letter in a variable and and remove that letter using slicing after that add that letter at the end of the word. Finally add "ma" and "a" accordingly.\nAny suggestions or feedbacks are welcome.\n\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n vwl_lst = [\'a\',\'e\',\'i\',\'o\',\'u\',\'A\',\'E\',\'I\',\'O\',\'U\']\n \n sentence = sentence.split()\n \n for i in range(len(sentence)):\n if sentence[i][0] in vwl_lst:\n \n sentence[i] = sentence[i]+"ma"+ ("a"*(i+1))\n else:\n a = sentence[i][0]\n sentence[i] = sentence[i][1:]\n sentence[i] = sentence[i]+a\n sentence[i] = sentence[i]+"ma"+("a"*(i+1))\n \n return \' \'.join(sentence)\n```
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Simple solution
goat-latin
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)$$ -->\n\n# Code\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n vowels = (\'a\', \'e\', \'i\', \'o\', \'u\')\n splitted = sentence.split(" ")\n res = []\n for index, word in enumerate(splitted):\n if word[0].lower() in vowels:\n word_new = word + \'ma\' + (index + 1) * \'a\'\n res.append(word_new)\n else:\n word_new = word[1:] + word[0] + \'ma\' + (index + 1) * \'a\'\n res.append(word_new)\n return \' \'.join(res)\n```
0
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
Simple solution
goat-latin
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)$$ -->\n\n# Code\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n vowels = (\'a\', \'e\', \'i\', \'o\', \'u\')\n splitted = sentence.split(" ")\n res = []\n for index, word in enumerate(splitted):\n if word[0].lower() in vowels:\n word_new = word + \'ma\' + (index + 1) * \'a\'\n res.append(word_new)\n else:\n word_new = word[1:] + word[0] + \'ma\' + (index + 1) * \'a\'\n res.append(word_new)\n return \' \'.join(res)\n```
0
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Super Easy solution in O(N) time
goat-latin
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. -->\n1. split the string and convert it into array of strings\n2. Create a list of vowels which includes both uppercase and lowercase vowels\n3. check if the strings first letter a vowels and then add \'ma\' string to it with \'a\' based on value of i\n4. if the string is not vowel then remove the first character from the string and add at the end , then add \'a\'*i to it\n5. At last return the string with join function\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity = O(n)\nwhere n is size of res.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity = O(m+n)\nwhere m is size of vowerls and n is size of res\n\n# Code\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n res = sentence.split()\n ans = \'\'\n val = \'ma\'\n vowels = {\'a\',\'e\',\'i\',\'o\',\'u\',\'A\',\'E\',\'I\',\'O\',\'U\'}\n print(res)\n for i in range(len(res)):\n if res[i][0] in vowels:\n res[i]+= val\n res[i]+= \'a\'*i\n\n else:\n temp = res[i] \n temp = temp[1:]+temp[0]+val+(\'a\'*i)\n res[i] = temp \n\n res[i]+=\'a\'\n \n\n print(res)\n return \' \'.join(res)\n \n```
0
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
Super Easy solution in O(N) time
goat-latin
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. -->\n1. split the string and convert it into array of strings\n2. Create a list of vowels which includes both uppercase and lowercase vowels\n3. check if the strings first letter a vowels and then add \'ma\' string to it with \'a\' based on value of i\n4. if the string is not vowel then remove the first character from the string and add at the end , then add \'a\'*i to it\n5. At last return the string with join function\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity = O(n)\nwhere n is size of res.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity = O(m+n)\nwhere m is size of vowerls and n is size of res\n\n# Code\n```\nclass Solution:\n def toGoatLatin(self, sentence: str) -> str:\n res = sentence.split()\n ans = \'\'\n val = \'ma\'\n vowels = {\'a\',\'e\',\'i\',\'o\',\'u\',\'A\',\'E\',\'I\',\'O\',\'U\'}\n print(res)\n for i in range(len(res)):\n if res[i][0] in vowels:\n res[i]+= val\n res[i]+= \'a\'*i\n\n else:\n temp = res[i] \n temp = temp[1:]+temp[0]+val+(\'a\'*i)\n res[i] = temp \n\n res[i]+=\'a\'\n \n\n print(res)\n return \' \'.join(res)\n \n```
0
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Solution
friends-of-appropriate-ages
1
1
```C++ []\nclass Solution {\npublic:\n int numFriendRequests(vector<int>& ages) {\n vector<int> v(121, 0);\n for(auto it: ages)\n v[it]++;\n int ans=0;\n for(int i=1; i<121; i++)\n {\n if(v[i]==0) continue;\n int tmp =0;\n for(int j=1; j<121; j++)\n {\n if(v[j]==0) continue;\n if(i==j)\n {\n if(j>(i*0.5+7))\n tmp+=(v[i]-1);\n }\n else\n {\n bool flag= true;\n if(j<=(i*0.5+7)) flag= false;\n if(j>i) flag= false;\n if(i<100 && j>100) flag= false;\n if(flag)\n tmp+=v[j];\n }\n }\n ans= ans + v[i]*tmp;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass FriendRequest:\n def _binarySearch(self, ages, target):\n lo = 0\n hi = len(ages) - 1\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n if ages[mid] <= target:\n lo = mid + 1\n else:\n hi = mid - 1\n return lo\n \n def numOfRequests(self, ages):\n requests = 0\n ages.sort()\n for age in ages:\n left = self._binarySearch(ages, age // 2 + 7)\n right = self._binarySearch(ages, age) - 1\n requests += max(0, right - left)\n return requests\n\nclass FriendRequest2:\n def _bucketSort(self, ages):\n buckets = [0] * 121\n for age in ages:\n buckets[age] += 1\n return buckets\n \n def _buildPrefixSum(self, buckets):\n prefix = [0] * 121\n for i in range(1, 121):\n prefix[i] += prefix[i - 1] + buckets[i]\n return prefix\n \n def numOfRequests(self, ages):\n buckets = self._bucketSort(ages)\n prefix = self._buildPrefixSum(buckets)\n requests = 0\n for age in range(15, 121):\n if buckets[age] == 0:\n continue\n cur_requests = prefix[age] - prefix[age // 2 + 7]\n requests += buckets[age] * cur_requests - buckets[age]\n return requests\n\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n return FriendRequest2().numOfRequests(ages)\n```\n\n```Java []\nclass Solution {\n public int numFriendRequests(int[] ages) {\n int res = 0;\n int[] numInAge = new int[121], sumInAge = new int[121];\n for(int a : ages) {\n numInAge[a]++;\n }\n for(int i = 1; i <= 120; i++) {\n sumInAge[i] = numInAge[i] + sumInAge[i-1];\n }\n for(int i = 15; i <= 120; i++) {\n if (numInAge[i] == 0) continue;\n int c = sumInAge[i] - sumInAge[i/2 + 7];\n res += c * numInAge[i] - numInAge[i];\n }\n return res;\n }\n}\n```\n
1
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Solution
friends-of-appropriate-ages
1
1
```C++ []\nclass Solution {\npublic:\n int numFriendRequests(vector<int>& ages) {\n vector<int> v(121, 0);\n for(auto it: ages)\n v[it]++;\n int ans=0;\n for(int i=1; i<121; i++)\n {\n if(v[i]==0) continue;\n int tmp =0;\n for(int j=1; j<121; j++)\n {\n if(v[j]==0) continue;\n if(i==j)\n {\n if(j>(i*0.5+7))\n tmp+=(v[i]-1);\n }\n else\n {\n bool flag= true;\n if(j<=(i*0.5+7)) flag= false;\n if(j>i) flag= false;\n if(i<100 && j>100) flag= false;\n if(flag)\n tmp+=v[j];\n }\n }\n ans= ans + v[i]*tmp;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass FriendRequest:\n def _binarySearch(self, ages, target):\n lo = 0\n hi = len(ages) - 1\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n if ages[mid] <= target:\n lo = mid + 1\n else:\n hi = mid - 1\n return lo\n \n def numOfRequests(self, ages):\n requests = 0\n ages.sort()\n for age in ages:\n left = self._binarySearch(ages, age // 2 + 7)\n right = self._binarySearch(ages, age) - 1\n requests += max(0, right - left)\n return requests\n\nclass FriendRequest2:\n def _bucketSort(self, ages):\n buckets = [0] * 121\n for age in ages:\n buckets[age] += 1\n return buckets\n \n def _buildPrefixSum(self, buckets):\n prefix = [0] * 121\n for i in range(1, 121):\n prefix[i] += prefix[i - 1] + buckets[i]\n return prefix\n \n def numOfRequests(self, ages):\n buckets = self._bucketSort(ages)\n prefix = self._buildPrefixSum(buckets)\n requests = 0\n for age in range(15, 121):\n if buckets[age] == 0:\n continue\n cur_requests = prefix[age] - prefix[age // 2 + 7]\n requests += buckets[age] * cur_requests - buckets[age]\n return requests\n\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n return FriendRequest2().numOfRequests(ages)\n```\n\n```Java []\nclass Solution {\n public int numFriendRequests(int[] ages) {\n int res = 0;\n int[] numInAge = new int[121], sumInAge = new int[121];\n for(int a : ages) {\n numInAge[a]++;\n }\n for(int i = 1; i <= 120; i++) {\n sumInAge[i] = numInAge[i] + sumInAge[i-1];\n }\n for(int i = 15; i <= 120; i++) {\n if (numInAge[i] == 0) continue;\n int c = sumInAge[i] - sumInAge[i/2 + 7];\n res += c * numInAge[i] - numInAge[i];\n }\n return res;\n }\n}\n```\n
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python 3 | Three Methods (Binary Search, Counter/Hashmap, Math) | Explanation
friends-of-appropriate-ages
0
1
### Approach 1. Binary Search + Math\n- Time Complexity: `O(NlogN), N = len(ages)`\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n ages.sort() # sort the `ages`\n ans = 0\n n = len(ages)\n for idx, age in enumerate(ages): # for each age\n lb = age # lower bound\n ub = (age - 7) * 2 # upper bound\n i = bisect.bisect_left(ages, lb) # binary search lower bound\n j = bisect.bisect_left(ages, ub) # binary search upper bound\n if j - i <= 0: continue\n ans += j - i # count number of potential friends\n if lb <= age < ub: # ignore itself\n ans -= 1\n return ans\n```\n### Approach 2. Counter + Nested loop\n- Time complexity: `max(O(121*121), N), N = len(ages)`\n```\nclass Solution(object):\n def numFriendRequests(self, ages):\n count = [0] * 121 # counter: count frequency of each age\n for age in ages:\n count[age] += 1\n ans = 0\n for ageA, countA in enumerate(count): # nested loop, pretty straightforward\n for ageB, countB in enumerate(count):\n if ageA * 0.5 + 7 >= ageB: continue\n if ageA < ageB: continue\n if ageA < 100 < ageB: continue\n ans += countA * countB\n if ageA == ageB: ans -= countA\n return ans \n```\t\t\n### Approach 3. Counter + Binary Search + Math\n- Time complexity: `max(O(121*log(121)), N), N = len(ages)`\n```\nclass Solution:\n def numFriendRequests(self, ages):\n count = [0] * 121 # counter: count frequency of each age\n for age in ages:\n count[age] += 1\n prefix = [0] * 121 # prefix-sum: prefix sum of frequency, we will use this for range subtraction\n for i in range(1, 121):\n prefix[i] = prefix[i-1] + count[i]\n nums = [i for i in range(121)] # a dummy age list, which will be used in binary search\n ans = 0\n for age, cnt in enumerate(count):\n if not cnt: continue\n lb = age # lower bound\n ub = (age - 7) * 2 # upper bound\n i = bisect.bisect_left(nums, lb) # binary search on lower bound, O(log(121))\n j = bisect.bisect_left(nums, ub) # binary search on upper bound, O(log(121))\n if j - i <= 0: continue\n total = prefix[j-1] - prefix[i-1] # range subtraction - how many ages in total can be considered as friend, including current age itself\n if lb <= age < ub: # considering itself, e.g. [17, 17, 17]\n # total -= cnt # minus itself\n # total = (cnt - 1) * cnt + total * cnt # make friends with other at same age `(cnt-1) * cnt`; with other at different age `total * cnt`\n total = cnt * (total - 1) # a cleaner presentation of above two lines\n ans += total \n return ans\n```
9
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Python 3 | Three Methods (Binary Search, Counter/Hashmap, Math) | Explanation
friends-of-appropriate-ages
0
1
### Approach 1. Binary Search + Math\n- Time Complexity: `O(NlogN), N = len(ages)`\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n ages.sort() # sort the `ages`\n ans = 0\n n = len(ages)\n for idx, age in enumerate(ages): # for each age\n lb = age # lower bound\n ub = (age - 7) * 2 # upper bound\n i = bisect.bisect_left(ages, lb) # binary search lower bound\n j = bisect.bisect_left(ages, ub) # binary search upper bound\n if j - i <= 0: continue\n ans += j - i # count number of potential friends\n if lb <= age < ub: # ignore itself\n ans -= 1\n return ans\n```\n### Approach 2. Counter + Nested loop\n- Time complexity: `max(O(121*121), N), N = len(ages)`\n```\nclass Solution(object):\n def numFriendRequests(self, ages):\n count = [0] * 121 # counter: count frequency of each age\n for age in ages:\n count[age] += 1\n ans = 0\n for ageA, countA in enumerate(count): # nested loop, pretty straightforward\n for ageB, countB in enumerate(count):\n if ageA * 0.5 + 7 >= ageB: continue\n if ageA < ageB: continue\n if ageA < 100 < ageB: continue\n ans += countA * countB\n if ageA == ageB: ans -= countA\n return ans \n```\t\t\n### Approach 3. Counter + Binary Search + Math\n- Time complexity: `max(O(121*log(121)), N), N = len(ages)`\n```\nclass Solution:\n def numFriendRequests(self, ages):\n count = [0] * 121 # counter: count frequency of each age\n for age in ages:\n count[age] += 1\n prefix = [0] * 121 # prefix-sum: prefix sum of frequency, we will use this for range subtraction\n for i in range(1, 121):\n prefix[i] = prefix[i-1] + count[i]\n nums = [i for i in range(121)] # a dummy age list, which will be used in binary search\n ans = 0\n for age, cnt in enumerate(count):\n if not cnt: continue\n lb = age # lower bound\n ub = (age - 7) * 2 # upper bound\n i = bisect.bisect_left(nums, lb) # binary search on lower bound, O(log(121))\n j = bisect.bisect_left(nums, ub) # binary search on upper bound, O(log(121))\n if j - i <= 0: continue\n total = prefix[j-1] - prefix[i-1] # range subtraction - how many ages in total can be considered as friend, including current age itself\n if lb <= age < ub: # considering itself, e.g. [17, 17, 17]\n # total -= cnt # minus itself\n # total = (cnt - 1) * cnt + total * cnt # make friends with other at same age `(cnt-1) * cnt`; with other at different age `total * cnt`\n total = cnt * (total - 1) # a cleaner presentation of above two lines\n ans += total \n return ans\n```
9
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Simple Python solution beats 88%
friends-of-appropriate-ages
0
1
\n def numFriendRequests(self, ages: List[int]) -> int:\n\t # send request or not\n def request(x,y):\n if y <= 0.5 * x + 7 or y > x or (y > 100 and x < 100):\n return False\n return True\n \n\t\t# Construct a dictionary that the keys are ages and the values are the frequency of the age in the list. \n ages_map = collections.Counter(ages)\n\t\t\n\t\t# Sort age list\n ages = list(ages_map.keys())\n ages.sort(reverse=True)\n\n count = 0\n for i in range(len(ages)):\n for j in range(i+1,len(ages)):\n\t\t\t# Different age: {a:2, b:3}\n\t\t\t# a --> b : number of a * number of b\n if request(ages[i],ages[j]):\n count += ages_map[ages[i]]* ages_map[ages[j]]\n # Same age: {a:2}\n\t\t\t# a --> a: n * (n -1)\n\t\t\t\t# example1 : [16, 16, 16]: request --> True --> 3 * (3-1) = 6\n\t\t\t\t# example2: [6,6] : request --> False \n if request(ages[i],ages[i]):\n count += ages_map[ages[i]]*(ages_map[ages[i]]-1)\n return count\n
2
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Simple Python solution beats 88%
friends-of-appropriate-ages
0
1
\n def numFriendRequests(self, ages: List[int]) -> int:\n\t # send request or not\n def request(x,y):\n if y <= 0.5 * x + 7 or y > x or (y > 100 and x < 100):\n return False\n return True\n \n\t\t# Construct a dictionary that the keys are ages and the values are the frequency of the age in the list. \n ages_map = collections.Counter(ages)\n\t\t\n\t\t# Sort age list\n ages = list(ages_map.keys())\n ages.sort(reverse=True)\n\n count = 0\n for i in range(len(ages)):\n for j in range(i+1,len(ages)):\n\t\t\t# Different age: {a:2, b:3}\n\t\t\t# a --> b : number of a * number of b\n if request(ages[i],ages[j]):\n count += ages_map[ages[i]]* ages_map[ages[j]]\n # Same age: {a:2}\n\t\t\t# a --> a: n * (n -1)\n\t\t\t\t# example1 : [16, 16, 16]: request --> True --> 3 * (3-1) = 6\n\t\t\t\t# example2: [6,6] : request --> False \n if request(ages[i],ages[i]):\n count += ages_map[ages[i]]*(ages_map[ages[i]]-1)\n return count\n
2
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python simple solution using counters beats 85%
friends-of-appropriate-ages
0
1
### Algorithm\n**Step 1**: construct a dictionary with age as key and number of members in that age group as values. This can be done using Counter in collections module.\n**Step 2**: iterate for every age group (not every person!!) say "me"\n**Step 3**: for every age group check condition take ("age","me") pair and check if the conditions asked are satisfied with \n* age<= 0.5 * me +7\n* age>me\n* 3rd condition is always false so we can omit it.\n\n**Step 4**:\nHere we have 2 cases.\n* **case(a): if your age is different from the other age**\nfor example 16,15,15 then 15->16 and 15->16\n\t\tie 2\\*1 which is `age_count * me_count`\n* **case(b): if your age is same as other age**\nfor example 16,16 then 16<->16 ie 2. \nThis would be same as number of edges in a graph with n vertices where each edge considered 2 times which is 2\\*nC2 which would be `me_count*(me_count-1)`\n### Python code\n```\nfrom collections import Counter\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n count=0\n\t\t# Step 1\n dicto=Counter(ages)\n\t\t# Step 2\n for me in dicto:\n my_age_count=dicto[me]\n\t\t\t# Step 3\n for age in dicto:\n if not (age<= 0.5 * me +7 or age>me):\n\t\t\t\t\t# Step 4 case (a)\n if age!=me :\n count+=dicto[age]*my_age_count\n\t\t\t\t\t# Step 4 case (b)\n else:\n count+=int(my_age_count*(my_age_count-1))\n return count\n```
9
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Python simple solution using counters beats 85%
friends-of-appropriate-ages
0
1
### Algorithm\n**Step 1**: construct a dictionary with age as key and number of members in that age group as values. This can be done using Counter in collections module.\n**Step 2**: iterate for every age group (not every person!!) say "me"\n**Step 3**: for every age group check condition take ("age","me") pair and check if the conditions asked are satisfied with \n* age<= 0.5 * me +7\n* age>me\n* 3rd condition is always false so we can omit it.\n\n**Step 4**:\nHere we have 2 cases.\n* **case(a): if your age is different from the other age**\nfor example 16,15,15 then 15->16 and 15->16\n\t\tie 2\\*1 which is `age_count * me_count`\n* **case(b): if your age is same as other age**\nfor example 16,16 then 16<->16 ie 2. \nThis would be same as number of edges in a graph with n vertices where each edge considered 2 times which is 2\\*nC2 which would be `me_count*(me_count-1)`\n### Python code\n```\nfrom collections import Counter\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n count=0\n\t\t# Step 1\n dicto=Counter(ages)\n\t\t# Step 2\n for me in dicto:\n my_age_count=dicto[me]\n\t\t\t# Step 3\n for age in dicto:\n if not (age<= 0.5 * me +7 or age>me):\n\t\t\t\t\t# Step 4 case (a)\n if age!=me :\n count+=dicto[age]*my_age_count\n\t\t\t\t\t# Step 4 case (b)\n else:\n count+=int(my_age_count*(my_age_count-1))\n return count\n```
9
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python - O(N) time, O(1) space. Better than 92%, simple prefix sum approach
friends-of-appropriate-ages
0
1
# Intuition\nWe focus on discovering how many people can a person of certain age request friendship. It turns out, a person Y can request ALL peoples that fall into ages that respect:\n\n1. age < Y\'s age\n2. age > (Y\'s age) // 2 + 7\n\nWe just need to find how many people fall into those constraints and sum the result.\n\n# Approach\nWe calculate a prefix sum of how many people fall into a certain range of age. That\'s described in the following lines:\n\n```\namount_in_ages = [0] * 121\ntotal_amount_until = [0] * 121\nunique_ages = set()\n\nfor age in ages:\n amount_in_ages[age] += 1\n unique_ages.add(age)\n\nfor i in range(1, len(amount_in_ages)):\n total_amount_until[i] = total_amount_until[i - 1] + amount_in_ages[i]\n```\n\nWe store how many people we have for a specific certain age in `amount_in_ages`, `while total_amount_until` will have the amount of people until (including) the `ith` age, such that total_amount_until[y] - total_amount_until[x] will return the amount of people within ages Y and X, assuming that Y > X.\n\nWe then iterate over each unique age, and multiply the amount of requests, since people of the same age will make the same amount of requests. \n\n```\nrequests = amount_in_ages[age] * (total_amount_until[hb] - total_amount_until[lb] - 1)\ntotal_requests += max(0, requests)\n```\n\nWe subtract by one because the person will always fall into the range that it can send requests to, se we avoid a person requesting itself.\n\n# Complexity\n- Time complexity:\nO(N), as we need to iterate over the whole array\n\n- Space complexity:\nO(1), we always use 121 spaces.\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n amount_in_ages = [0] * 121\n total_amount_until = [0] * 121\n unique_ages = set()\n \n for age in ages:\n amount_in_ages[age] += 1\n unique_ages.add(age)\n\n for i in range(1, len(amount_in_ages)):\n total_amount_until[i] = total_amount_until[i - 1] + amount_in_ages[i]\n\n total_requests = 0\n\n for age in unique_ages: \n lb = max(age // 2 + 7, 0)\n hb = age\n\n if lb <= hb:\n requests = amount_in_ages[age] * (total_amount_until[hb] - total_amount_until[lb] - 1)\n total_requests += max(0, requests)\n\n return total_requests\n```
0
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Python - O(N) time, O(1) space. Better than 92%, simple prefix sum approach
friends-of-appropriate-ages
0
1
# Intuition\nWe focus on discovering how many people can a person of certain age request friendship. It turns out, a person Y can request ALL peoples that fall into ages that respect:\n\n1. age < Y\'s age\n2. age > (Y\'s age) // 2 + 7\n\nWe just need to find how many people fall into those constraints and sum the result.\n\n# Approach\nWe calculate a prefix sum of how many people fall into a certain range of age. That\'s described in the following lines:\n\n```\namount_in_ages = [0] * 121\ntotal_amount_until = [0] * 121\nunique_ages = set()\n\nfor age in ages:\n amount_in_ages[age] += 1\n unique_ages.add(age)\n\nfor i in range(1, len(amount_in_ages)):\n total_amount_until[i] = total_amount_until[i - 1] + amount_in_ages[i]\n```\n\nWe store how many people we have for a specific certain age in `amount_in_ages`, `while total_amount_until` will have the amount of people until (including) the `ith` age, such that total_amount_until[y] - total_amount_until[x] will return the amount of people within ages Y and X, assuming that Y > X.\n\nWe then iterate over each unique age, and multiply the amount of requests, since people of the same age will make the same amount of requests. \n\n```\nrequests = amount_in_ages[age] * (total_amount_until[hb] - total_amount_until[lb] - 1)\ntotal_requests += max(0, requests)\n```\n\nWe subtract by one because the person will always fall into the range that it can send requests to, se we avoid a person requesting itself.\n\n# Complexity\n- Time complexity:\nO(N), as we need to iterate over the whole array\n\n- Space complexity:\nO(1), we always use 121 spaces.\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n amount_in_ages = [0] * 121\n total_amount_until = [0] * 121\n unique_ages = set()\n \n for age in ages:\n amount_in_ages[age] += 1\n unique_ages.add(age)\n\n for i in range(1, len(amount_in_ages)):\n total_amount_until[i] = total_amount_until[i - 1] + amount_in_ages[i]\n\n total_requests = 0\n\n for age in unique_ages: \n lb = max(age // 2 + 7, 0)\n hb = age\n\n if lb <= hb:\n requests = amount_in_ages[age] * (total_amount_until[hb] - total_amount_until[lb] - 1)\n total_requests += max(0, requests)\n\n return total_requests\n```
0
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python: O(n * log n) solution with binary search
friends-of-appropriate-ages
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)$$ -->\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n ages.sort()\n n = len(ages)\n nRequests = 0\n\n def bSearch(target, low, high):\n if low > high:\n return low\n mid = (low + high) // 2\n if ages[mid] > target:\n high = mid - 1\n else:\n low = mid + 1\n return bSearch(target, low, high)\n\n for i in range(n - 1, -1, -1):\n x = ages[i]\n j = bSearch(0.5 * x + 7, 0, i - 1)\n nRequests += i - j\n if x > 0.5 * x + 7:\n k = bSearch(x - 1, 0, i - 1)\n if ages[k] == x:\n nRequests += i - k\n\n return nRequests \n \n \n return nRequests\n\n \n```
0
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Python: O(n * log n) solution with binary search
friends-of-appropriate-ages
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)$$ -->\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n ages.sort()\n n = len(ages)\n nRequests = 0\n\n def bSearch(target, low, high):\n if low > high:\n return low\n mid = (low + high) // 2\n if ages[mid] > target:\n high = mid - 1\n else:\n low = mid + 1\n return bSearch(target, low, high)\n\n for i in range(n - 1, -1, -1):\n x = ages[i]\n j = bSearch(0.5 * x + 7, 0, i - 1)\n nRequests += i - j\n if x > 0.5 * x + 7:\n k = bSearch(x - 1, 0, i - 1)\n if ages[k] == x:\n nRequests += i - k\n\n return nRequests \n \n \n return nRequests\n\n \n```
0
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
O(n log n) solution using binary search
friends-of-appropriate-ages
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou can solve this problem with a brutal force with nested loops, but it will likely get TLE. So, an optimized solution is to sort the source data first. Then, calculate the valid request numbers by determining the start and end indices of valid range for each person x. Each range is defined by lower and upper bounds, which can be quickly determined using binary search algorithm. \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)$$ -->\nO(n log n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nimport bisect\n\nclass Solution:\n # O(n log n)\n def numFriendRequests(self, ages: List[int]) -> int:\n def lowerBound(x):\n return x * 0.5 + 7\n\n # sort the source data for applying binary search algorithm\n ages.sort() # O(n log n)\n count = 0\n for i in range(len(ages)):\n x = ages[i]\n \n # get the start and end indices using binary search algorithm\n lower = lowerBound(x) # find the lower bound \n start = bisect_right(ages, lower) # O(log n)\n end = bisect_right(ages, x) # O(log n) get the end index where the valud is equal x \n\n increase = end - start - 1 # get the valid person number, but exclusive x \n\n # only add the number of valid person if the value is positive\n if increase > 0:\n count += increase\n return count\n```
0
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
O(n log n) solution using binary search
friends-of-appropriate-ages
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou can solve this problem with a brutal force with nested loops, but it will likely get TLE. So, an optimized solution is to sort the source data first. Then, calculate the valid request numbers by determining the start and end indices of valid range for each person x. Each range is defined by lower and upper bounds, which can be quickly determined using binary search algorithm. \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)$$ -->\nO(n log n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nimport bisect\n\nclass Solution:\n # O(n log n)\n def numFriendRequests(self, ages: List[int]) -> int:\n def lowerBound(x):\n return x * 0.5 + 7\n\n # sort the source data for applying binary search algorithm\n ages.sort() # O(n log n)\n count = 0\n for i in range(len(ages)):\n x = ages[i]\n \n # get the start and end indices using binary search algorithm\n lower = lowerBound(x) # find the lower bound \n start = bisect_right(ages, lower) # O(log n)\n end = bisect_right(ages, x) # O(log n) get the end index where the valud is equal x \n\n increase = end - start - 1 # get the valid person number, but exclusive x \n\n # only add the number of valid person if the value is positive\n if increase > 0:\n count += increase\n return count\n```
0
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
100% Faster
friends-of-appropriate-ages
0
1
# Complexity\n- Time complexity: $$O(n)$$.\n\n- Space complexity: $$O(120)$$ ~ $$O(1)$$.\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n cntr = Counter(ages)\n ages, pSum = [], []\n for age, cnt in sorted(cntr.items()):\n ages.append(age)\n pSum.append((pSum[-1] if len(pSum) else 0) + cnt)\n \n result = 0\n for i, age in enumerate(ages):\n if age > 14:\n result += cntr[age]*(cntr[age] - 1)\n j = bisect_right(ages, 0.5*age + 7)\n if j < i:\n result += cntr[age]*(pSum[i-1] - (pSum[j-1] if j > 0 else 0))\n\n return result\n```
0
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
100% Faster
friends-of-appropriate-ages
0
1
# Complexity\n- Time complexity: $$O(n)$$.\n\n- Space complexity: $$O(120)$$ ~ $$O(1)$$.\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n cntr = Counter(ages)\n ages, pSum = [], []\n for age, cnt in sorted(cntr.items()):\n ages.append(age)\n pSum.append((pSum[-1] if len(pSum) else 0) + cnt)\n \n result = 0\n for i, age in enumerate(ages):\n if age > 14:\n result += cntr[age]*(cntr[age] - 1)\n j = bisect_right(ages, 0.5*age + 7)\n if j < i:\n result += cntr[age]*(pSum[i-1] - (pSum[j-1] if j > 0 else 0))\n\n return result\n```
0
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
bisect solution
friends-of-appropriate-ages
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)$$ -->\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n ages.sort()\n tot = 0 \n n = len(ages) \n left_idx = 0\n i = 0\n prev_age = 0\n same_age = 0\n\n for i in range(n):\n curr_age = ages[i]\n if curr_age <= 14:\n continue\n if prev_age == curr_age:\n same_age += 1\n else:\n prev_age = curr_age\n same_age = 0\n\n left_idx = bisect.bisect_right(ages, 0.5 * curr_age + 7, lo = left_idx, hi = n)\n\n tot += (i - left_idx - same_age) + 2 * same_age\n\n return tot\n\n```
0
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
bisect solution
friends-of-appropriate-ages
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)$$ -->\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n ages.sort()\n tot = 0 \n n = len(ages) \n left_idx = 0\n i = 0\n prev_age = 0\n same_age = 0\n\n for i in range(n):\n curr_age = ages[i]\n if curr_age <= 14:\n continue\n if prev_age == curr_age:\n same_age += 1\n else:\n prev_age = curr_age\n same_age = 0\n\n left_idx = bisect.bisect_right(ages, 0.5 * curr_age + 7, lo = left_idx, hi = n)\n\n tot += (i - left_idx - same_age) + 2 * same_age\n\n return tot\n\n```
0
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python - O(n)Time, O(n) Space
friends-of-appropriate-ages
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInstead of checking every age with every other age (O(n^2)) we can generate a range of appropriate ages for every age and check the count of each age in the range and add it to result. Make sure to subtract 1 from the count of same age to exclude the scenario of person sending request to themselves.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFind the counts of all the unique ages. Then for each age get a range of ages that are appropriate using the conditions in the problem statement. Iterate over the range of appropriate ages and get the count of that particular age and add it to result, if that age is same as the first person age subtract 1 from the answer to exclude the scenario of person sending a request to themselves.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(120 * n) ~ O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n age_counts = {}\n\n for age in ages:\n age_counts[age] = age_counts.get(age, 0) + 1\n\n res = 0\n\n for age in ages:\n lower_bound = int(0.5 * age) + 7\n upper_bound = age + 1\n\n for request_age in range(lower_bound + 1, upper_bound):\n res += age_counts.get(request_age, 0)\n if age == request_age:\n res -= 1\n\n return res\n\n \n```
0
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Python - O(n)Time, O(n) Space
friends-of-appropriate-ages
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInstead of checking every age with every other age (O(n^2)) we can generate a range of appropriate ages for every age and check the count of each age in the range and add it to result. Make sure to subtract 1 from the count of same age to exclude the scenario of person sending request to themselves.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFind the counts of all the unique ages. Then for each age get a range of ages that are appropriate using the conditions in the problem statement. Iterate over the range of appropriate ages and get the count of that particular age and add it to result, if that age is same as the first person age subtract 1 from the answer to exclude the scenario of person sending a request to themselves.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(120 * n) ~ O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n# Code\n```\nclass Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n age_counts = {}\n\n for age in ages:\n age_counts[age] = age_counts.get(age, 0) + 1\n\n res = 0\n\n for age in ages:\n lower_bound = int(0.5 * age) + 7\n upper_bound = age + 1\n\n for request_age in range(lower_bound + 1, upper_bound):\n res += age_counts.get(request_age, 0)\n if age == request_age:\n res -= 1\n\n return res\n\n \n```
0
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python Solution
most-profit-assigning-work
0
1
\n\n# Code\n```\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n d = {}\n # mapping the difficulty with the corresponding profit and then storing it in the dictionary\n for x in range(len(difficulty)) :\n if difficulty[x] in d :\n d[difficulty[x]] = max( d[difficulty[x]] , profit[x]) # overwriting with highest value\n else:\n d[difficulty[x]] = profit[x]\n\n # sorting the dictionary with respect to key\n dic = dict(sorted(d.items()))\n # sorting the difficulty also\n difficulty.sort()\n \n # now reassigning the profit with the max profit so far after sorting \n maxi = 0\n for x in dic.keys():\n maxi = max(maxi , dic[x] )\n dic[x] = maxi\n \n # calculating the total profit\n tot = 0\n for i in range(len(worker)) : \n # calculate the right position for the difficulty level of the workers\n r = bisect.bisect_left(difficulty,worker[i]) \n # if the position is at 0 then add the 0th profit only if the difficulty is equal \n if r==0: \n if difficulty[r] == worker[i] :\n tot += dic[difficulty[r]]\n else:\n tot += 0\n # if the difficulty is equal then add that profit \n elif r<len(difficulty) and difficulty[r] == worker[i] :\n tot += dic[difficulty[r]]\n # if the difficulty is not equal then add the previous profit \n else:\n tot += dic[difficulty[r-1]]\n return tot\n```
1
You have `n` jobs and `m` workers. You are given three arrays: `difficulty`, `profit`, and `worker` where: * `difficulty[i]` and `profit[i]` are the difficulty and the profit of the `ith` job, and * `worker[j]` is the ability of `jth` worker (i.e., the `jth` worker can only complete a job with difficulty at most `worker[j]`). Every worker can be assigned **at most one job**, but one job can be **completed multiple times**. * For example, if three workers attempt the same job that pays `$1`, then the total profit will be `$3`. If a worker cannot complete any job, their profit is `$0`. Return the maximum profit we can achieve after assigning the workers to the jobs. **Example 1:** **Input:** difficulty = \[2,4,6,8,10\], profit = \[10,20,30,40,50\], worker = \[4,5,6,7\] **Output:** 100 **Explanation:** Workers are assigned jobs of difficulty \[4,4,6,6\] and they get a profit of \[20,20,30,30\] separately. **Example 2:** **Input:** difficulty = \[85,47,57\], profit = \[24,66,99\], worker = \[40,25,25\] **Output:** 0 **Constraints:** * `n == difficulty.length` * `n == profit.length` * `m == worker.length` * `1 <= n, m <= 104` * `1 <= difficulty[i], profit[i], worker[i] <= 105`
null
Python Solution
most-profit-assigning-work
0
1
\n\n# Code\n```\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n d = {}\n # mapping the difficulty with the corresponding profit and then storing it in the dictionary\n for x in range(len(difficulty)) :\n if difficulty[x] in d :\n d[difficulty[x]] = max( d[difficulty[x]] , profit[x]) # overwriting with highest value\n else:\n d[difficulty[x]] = profit[x]\n\n # sorting the dictionary with respect to key\n dic = dict(sorted(d.items()))\n # sorting the difficulty also\n difficulty.sort()\n \n # now reassigning the profit with the max profit so far after sorting \n maxi = 0\n for x in dic.keys():\n maxi = max(maxi , dic[x] )\n dic[x] = maxi\n \n # calculating the total profit\n tot = 0\n for i in range(len(worker)) : \n # calculate the right position for the difficulty level of the workers\n r = bisect.bisect_left(difficulty,worker[i]) \n # if the position is at 0 then add the 0th profit only if the difficulty is equal \n if r==0: \n if difficulty[r] == worker[i] :\n tot += dic[difficulty[r]]\n else:\n tot += 0\n # if the difficulty is equal then add that profit \n elif r<len(difficulty) and difficulty[r] == worker[i] :\n tot += dic[difficulty[r]]\n # if the difficulty is not equal then add the previous profit \n else:\n tot += dic[difficulty[r-1]]\n return tot\n```
1
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
All Kind Of Solution With Explanation
most-profit-assigning-work
0
1
### All These Solutions except the very last one are inspired by @lee215 and @votrubac\n## Solution 1\n```\n1.Create a vector where each element is a pair comprised difficulty[i] and profit[i] for each i.\n2.Sort it and it will be sorted by difficulty[i] by default.\n3.Also sort the \'worker\', now for each worker[i] traverse \'jobs\' till jobs[j].first <= worker[i].\n We don\'t need to traverse \'j always from the beginning as \n "one job can be completed multiple times" means \n \n 10 20 10 5 - profit \n 4 5 7 9 - difficulty \n 2 4 8 10 - worker\n\n for worker[2] = 8, I can do difficulty : 4,5,7 but 5 pay me highest(20) so I\'ll take 5\n because I can do any job which difficulty level <= my difficulty level.\n So using max() we can easily find high paid level as we have "sorted jobs". \n \n Of course in pair difficult[i] is the first one cause we need to compare worker[i] with \n difficulty[i] and both denotes \'difficulty level\'.\n```\n\n```CPP []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {\n vector<pair<int,int>> jobs;\n for(int i=0; i<difficulty.size(); i++)\n jobs.push_back({difficulty[i],profit[i]});\n\n sort(begin(jobs),end(jobs));\n sort(begin(worker),end(worker));\n\n int j = 0, best = 0, sum = 0;\n for(int & it : worker)\n {\n while(j<jobs.size() && jobs[j].first<=it)\n best = max(best, jobs[j].second), j++;\n sum += best;\n }\n return sum;\n }\n};\n```\n```Python []\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n jobs = sorted(zip(difficulty, profit))\n j = best = ans = 0\n for ability in sorted(worker):\n while j < len(jobs) and jobs[j][0] <= ability:\n best = max(best, jobs[j][1])\n j += 1\n ans += best\n \n return ans\n```\n```\nTime complexity : O(nlogn)\nSpace complexity : O(n)\n```\n## Solution 2 :\n```\nmax(m[difficulty[i]], profit[i]) had done because there can be duplicate in \'difficulty\'.\n\nDifficulty Profit Profit\n---------- -------- ___________ --------\n 4 20 | | 20\n 6 10 ----> | Second | -----> 20\n 8 30 | For | 30\n 10 20 | Loop | 30\n\nreturn accumulate(begin(worker), end(worker), 0, [m](int sum, int value)...\n |\n sum = -------------------------\n and value = each value in worker\n \n 1 2 4 5 8 9\n upper_bound(5) = 8 \n lower_bound(5) = 5 but\n 1 2 4 8 9\n lower_bound(5) = 8. Upper_bound = 1 variation where lower_bound = 2 variation.\nThat\'s why upper_bound chosen. prev(upper_bound(iterator)) is the iterator we need here always.\n```\n```CPP []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) \n {\n map<int, int> m;\n for(int i=0; i<difficulty.size(); i++)\n m[difficulty[i]] = max(m[difficulty[i]], profit[i]);\n \n for(auto it = next(m.begin()); it!= m.end(); it++)\n it->second = max(prev(it)->second, it->second);\n \n return accumulate(begin(worker), end(worker), 0, [m](int sum, int value){ return sum + prev(m.upper_bound(value))->second; });\n }\n};\n```\n```\nTime Complexity : O(nlogn) as we took map.\nSpace Complexity : O(n)\n```\n## Solution 3 :\n```\nHere difficulty[i] = index and profit[i] = value of the " counting sort \'jobs\' "\n\ndifficulty = [2,4,6,8,10], profit = [20,10,15,40,30], worker = [4,5,6,7]\n\n0 0 20 0 10 0 15 0 40 0 50 ............. (profit)\n0 1 2 3 4 5 6 7 8 9 10 ............. (difficulty)\n \n * After the second for loop *\n \n0 0 20 20 20 20 20 20 40 40 40 ............. (profit)\n0 1 2 3 4 5 6 7 8 9 10 ............. (difficulty)\n\nIn the map solution when we "accumulate"d for each worker[i] say for 5 we had to go for \nprev(upper_bound) = prev(5) = 4 here, but here in counting sort we have 5 to access directly, \n\n \' 20 (profit)\n 5 (difficulty) \'\n\nwe don\'t need any upper bound or traversing the array to get the value. So this solution is fast.\n```\n```CPP []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) \n {\n int jobs[100001] = {0};\n for(int i=0; i<difficulty.size(); i++)\n jobs[difficulty[i]] = max(jobs[difficulty[i]], profit[i]);\n\n for(int i=1; i<100001; i++)\n jobs[i] = max(jobs[i], jobs[i-1]);\n\n return accumulate(begin(worker), end(worker), 0, [jobs](int s, int v){ return s + jobs[v]; });\n }\n};\n```\n```\nYou can also optimize it by below. We only need the maximum element of \'worker\'.\n 2 4 6 8 9 10 (difficulty)\n 2 3 5 7 (worker)\nas we need till \'7\', so we don\'t care values > 7 in \'difficulty\'. \nMake sure the value in \'difficulty\' is <= the maximum in \'worker\'.\n```\n```CPP []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) \n {\n int m = *max_element(begin(worker), end(worker)) + 1;\n vector<int> jobs(m, 0);\n for(int i=0; i<difficulty.size(); i++)\n if(difficulty[i] < m)\n jobs[difficulty[i]] = max(jobs[difficulty[i]], profit[i]);\n\n for(int i=1; i<m ;i++)\n jobs[i] = max(jobs[i], jobs[i-1]);\n\n return accumulate(begin(worker), end(worker), 0, [jobs](int s, int v){ return s + jobs[v]; });\n }\n};\n```\n```\nTime Complexity : O(n + m)\nSpace Complexity : O(m)\n```\n## If the post was helpful an upvote will really make me happy:)
2
You have `n` jobs and `m` workers. You are given three arrays: `difficulty`, `profit`, and `worker` where: * `difficulty[i]` and `profit[i]` are the difficulty and the profit of the `ith` job, and * `worker[j]` is the ability of `jth` worker (i.e., the `jth` worker can only complete a job with difficulty at most `worker[j]`). Every worker can be assigned **at most one job**, but one job can be **completed multiple times**. * For example, if three workers attempt the same job that pays `$1`, then the total profit will be `$3`. If a worker cannot complete any job, their profit is `$0`. Return the maximum profit we can achieve after assigning the workers to the jobs. **Example 1:** **Input:** difficulty = \[2,4,6,8,10\], profit = \[10,20,30,40,50\], worker = \[4,5,6,7\] **Output:** 100 **Explanation:** Workers are assigned jobs of difficulty \[4,4,6,6\] and they get a profit of \[20,20,30,30\] separately. **Example 2:** **Input:** difficulty = \[85,47,57\], profit = \[24,66,99\], worker = \[40,25,25\] **Output:** 0 **Constraints:** * `n == difficulty.length` * `n == profit.length` * `m == worker.length` * `1 <= n, m <= 104` * `1 <= difficulty[i], profit[i], worker[i] <= 105`
null
All Kind Of Solution With Explanation
most-profit-assigning-work
0
1
### All These Solutions except the very last one are inspired by @lee215 and @votrubac\n## Solution 1\n```\n1.Create a vector where each element is a pair comprised difficulty[i] and profit[i] for each i.\n2.Sort it and it will be sorted by difficulty[i] by default.\n3.Also sort the \'worker\', now for each worker[i] traverse \'jobs\' till jobs[j].first <= worker[i].\n We don\'t need to traverse \'j always from the beginning as \n "one job can be completed multiple times" means \n \n 10 20 10 5 - profit \n 4 5 7 9 - difficulty \n 2 4 8 10 - worker\n\n for worker[2] = 8, I can do difficulty : 4,5,7 but 5 pay me highest(20) so I\'ll take 5\n because I can do any job which difficulty level <= my difficulty level.\n So using max() we can easily find high paid level as we have "sorted jobs". \n \n Of course in pair difficult[i] is the first one cause we need to compare worker[i] with \n difficulty[i] and both denotes \'difficulty level\'.\n```\n\n```CPP []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {\n vector<pair<int,int>> jobs;\n for(int i=0; i<difficulty.size(); i++)\n jobs.push_back({difficulty[i],profit[i]});\n\n sort(begin(jobs),end(jobs));\n sort(begin(worker),end(worker));\n\n int j = 0, best = 0, sum = 0;\n for(int & it : worker)\n {\n while(j<jobs.size() && jobs[j].first<=it)\n best = max(best, jobs[j].second), j++;\n sum += best;\n }\n return sum;\n }\n};\n```\n```Python []\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n jobs = sorted(zip(difficulty, profit))\n j = best = ans = 0\n for ability in sorted(worker):\n while j < len(jobs) and jobs[j][0] <= ability:\n best = max(best, jobs[j][1])\n j += 1\n ans += best\n \n return ans\n```\n```\nTime complexity : O(nlogn)\nSpace complexity : O(n)\n```\n## Solution 2 :\n```\nmax(m[difficulty[i]], profit[i]) had done because there can be duplicate in \'difficulty\'.\n\nDifficulty Profit Profit\n---------- -------- ___________ --------\n 4 20 | | 20\n 6 10 ----> | Second | -----> 20\n 8 30 | For | 30\n 10 20 | Loop | 30\n\nreturn accumulate(begin(worker), end(worker), 0, [m](int sum, int value)...\n |\n sum = -------------------------\n and value = each value in worker\n \n 1 2 4 5 8 9\n upper_bound(5) = 8 \n lower_bound(5) = 5 but\n 1 2 4 8 9\n lower_bound(5) = 8. Upper_bound = 1 variation where lower_bound = 2 variation.\nThat\'s why upper_bound chosen. prev(upper_bound(iterator)) is the iterator we need here always.\n```\n```CPP []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) \n {\n map<int, int> m;\n for(int i=0; i<difficulty.size(); i++)\n m[difficulty[i]] = max(m[difficulty[i]], profit[i]);\n \n for(auto it = next(m.begin()); it!= m.end(); it++)\n it->second = max(prev(it)->second, it->second);\n \n return accumulate(begin(worker), end(worker), 0, [m](int sum, int value){ return sum + prev(m.upper_bound(value))->second; });\n }\n};\n```\n```\nTime Complexity : O(nlogn) as we took map.\nSpace Complexity : O(n)\n```\n## Solution 3 :\n```\nHere difficulty[i] = index and profit[i] = value of the " counting sort \'jobs\' "\n\ndifficulty = [2,4,6,8,10], profit = [20,10,15,40,30], worker = [4,5,6,7]\n\n0 0 20 0 10 0 15 0 40 0 50 ............. (profit)\n0 1 2 3 4 5 6 7 8 9 10 ............. (difficulty)\n \n * After the second for loop *\n \n0 0 20 20 20 20 20 20 40 40 40 ............. (profit)\n0 1 2 3 4 5 6 7 8 9 10 ............. (difficulty)\n\nIn the map solution when we "accumulate"d for each worker[i] say for 5 we had to go for \nprev(upper_bound) = prev(5) = 4 here, but here in counting sort we have 5 to access directly, \n\n \' 20 (profit)\n 5 (difficulty) \'\n\nwe don\'t need any upper bound or traversing the array to get the value. So this solution is fast.\n```\n```CPP []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) \n {\n int jobs[100001] = {0};\n for(int i=0; i<difficulty.size(); i++)\n jobs[difficulty[i]] = max(jobs[difficulty[i]], profit[i]);\n\n for(int i=1; i<100001; i++)\n jobs[i] = max(jobs[i], jobs[i-1]);\n\n return accumulate(begin(worker), end(worker), 0, [jobs](int s, int v){ return s + jobs[v]; });\n }\n};\n```\n```\nYou can also optimize it by below. We only need the maximum element of \'worker\'.\n 2 4 6 8 9 10 (difficulty)\n 2 3 5 7 (worker)\nas we need till \'7\', so we don\'t care values > 7 in \'difficulty\'. \nMake sure the value in \'difficulty\' is <= the maximum in \'worker\'.\n```\n```CPP []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) \n {\n int m = *max_element(begin(worker), end(worker)) + 1;\n vector<int> jobs(m, 0);\n for(int i=0; i<difficulty.size(); i++)\n if(difficulty[i] < m)\n jobs[difficulty[i]] = max(jobs[difficulty[i]], profit[i]);\n\n for(int i=1; i<m ;i++)\n jobs[i] = max(jobs[i], jobs[i-1]);\n\n return accumulate(begin(worker), end(worker), 0, [jobs](int s, int v){ return s + jobs[v]; });\n }\n};\n```\n```\nTime Complexity : O(n + m)\nSpace Complexity : O(m)\n```\n## If the post was helpful an upvote will really make me happy:)
2
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Python|| Binary Search Solution Easy to understand
most-profit-assigning-work
0
1
```\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n """\n idea: \n - zip difficulty and profit\n - sort by difficulty \n \n - iterate through each worker\'s ability (worker)\n - find the greatest difficulty using binary search , returning the high (bisect right)\n - max_profit += profit_of_worker[index found with binary search]\n """\n diff_prof = [list(i) for i in zip(difficulty, profit)]\n diff_prof.sort(key = lambda x: x[0])\n\t\t\n # need to make profit be the max up to i\n prev = diff_prof[0][1]\n for i in range(len(diff_prof)):\n diff_prof[i][1] = max(diff_prof[i][1], prev)\n prev = diff_prof[i][1]\n\n max_profit = 0\n for ability in worker:\n index = self.binary_search(diff_prof, ability)\n if index >= 0 and index < len(diff_prof):\n max_profit += diff_prof[index][1]\n return max_profit\n \n \n def binary_search(self, diff_prof: List, ability: int) -> int:\n lo, hi = 0 , len(diff_prof) - 1\n index = -1\n while lo <= hi:\n mid = (lo + (hi - lo)//2)\n #mid = (hi + lo) // 2\n if diff_prof[mid][0] <= ability:\n # save index of what a worker can do up to\n index = mid \n lo = mid + 1\n else:\n hi = mid - 1\n return index\n```
1
You have `n` jobs and `m` workers. You are given three arrays: `difficulty`, `profit`, and `worker` where: * `difficulty[i]` and `profit[i]` are the difficulty and the profit of the `ith` job, and * `worker[j]` is the ability of `jth` worker (i.e., the `jth` worker can only complete a job with difficulty at most `worker[j]`). Every worker can be assigned **at most one job**, but one job can be **completed multiple times**. * For example, if three workers attempt the same job that pays `$1`, then the total profit will be `$3`. If a worker cannot complete any job, their profit is `$0`. Return the maximum profit we can achieve after assigning the workers to the jobs. **Example 1:** **Input:** difficulty = \[2,4,6,8,10\], profit = \[10,20,30,40,50\], worker = \[4,5,6,7\] **Output:** 100 **Explanation:** Workers are assigned jobs of difficulty \[4,4,6,6\] and they get a profit of \[20,20,30,30\] separately. **Example 2:** **Input:** difficulty = \[85,47,57\], profit = \[24,66,99\], worker = \[40,25,25\] **Output:** 0 **Constraints:** * `n == difficulty.length` * `n == profit.length` * `m == worker.length` * `1 <= n, m <= 104` * `1 <= difficulty[i], profit[i], worker[i] <= 105`
null
Python|| Binary Search Solution Easy to understand
most-profit-assigning-work
0
1
```\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n """\n idea: \n - zip difficulty and profit\n - sort by difficulty \n \n - iterate through each worker\'s ability (worker)\n - find the greatest difficulty using binary search , returning the high (bisect right)\n - max_profit += profit_of_worker[index found with binary search]\n """\n diff_prof = [list(i) for i in zip(difficulty, profit)]\n diff_prof.sort(key = lambda x: x[0])\n\t\t\n # need to make profit be the max up to i\n prev = diff_prof[0][1]\n for i in range(len(diff_prof)):\n diff_prof[i][1] = max(diff_prof[i][1], prev)\n prev = diff_prof[i][1]\n\n max_profit = 0\n for ability in worker:\n index = self.binary_search(diff_prof, ability)\n if index >= 0 and index < len(diff_prof):\n max_profit += diff_prof[index][1]\n return max_profit\n \n \n def binary_search(self, diff_prof: List, ability: int) -> int:\n lo, hi = 0 , len(diff_prof) - 1\n index = -1\n while lo <= hi:\n mid = (lo + (hi - lo)//2)\n #mid = (hi + lo) // 2\n if diff_prof[mid][0] <= ability:\n # save index of what a worker can do up to\n index = mid \n lo = mid + 1\n else:\n hi = mid - 1\n return index\n```
1
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Python3 | Solved Using Binary Search W/ Sorting O((n+m)*logn) Runtime Solution!
most-profit-assigning-work
0
1
```\nclass Solution:\n #Time-Complexity: O(n + nlogn + n + mlog(n)) -> O((n+m) *logn)\n #Space-Complexity: O(n)\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n #Approach: First of all, linearly traverse each and every corresponding index\n #position of first two input arrays: difficulty and profit to group each\n #item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array\n #by increasing difficulty of the job! Then, for each worker, perform binary\n #search and consistently update the max profit the current worker can work and\n #earn! Add this value to answer variable, which is cumulative for all workers!\n #this will be the result returned at the end!\n arr = []\n for i in range(len(difficulty)):\n arr.append([difficulty[i], profit[i]])\n #sort by difficulty!\n arr.sort(key = lambda x: x[0])\n #then, I need to update the maximum profit up to each and every item!\n maximum = float(-inf)\n for j in range(len(arr)):\n maximum = max(maximum, arr[j][1])\n arr[j][1] = maximum\n ans = 0\n #iterate through each and every worker!\n for w in worker:\n bestProfit = 0\n #define search space to perform binary search!\n L, R = 0, len(arr) - 1\n #as long as search space has at least one element to consider or one job,\n #continue iterations of binary search!\n while L <= R:\n mid = (L + R) // 2\n mid_e = arr[mid]\n #check if current job has difficulty that is manageable!\n if(mid_e[0] <= w):\n bestProfit = max(bestProfit, mid_e[1])\n #we still need to search right and try higher difficulty\n #jobs that might yield higher profit!\n L = mid + 1\n continue\n else:\n R = mid - 1\n continue\n #once we break from while loop and end binary search, we should have\n #found bestProfit for current worker performing task that is manageable!\n ans += bestProfit\n return ans
4
You have `n` jobs and `m` workers. You are given three arrays: `difficulty`, `profit`, and `worker` where: * `difficulty[i]` and `profit[i]` are the difficulty and the profit of the `ith` job, and * `worker[j]` is the ability of `jth` worker (i.e., the `jth` worker can only complete a job with difficulty at most `worker[j]`). Every worker can be assigned **at most one job**, but one job can be **completed multiple times**. * For example, if three workers attempt the same job that pays `$1`, then the total profit will be `$3`. If a worker cannot complete any job, their profit is `$0`. Return the maximum profit we can achieve after assigning the workers to the jobs. **Example 1:** **Input:** difficulty = \[2,4,6,8,10\], profit = \[10,20,30,40,50\], worker = \[4,5,6,7\] **Output:** 100 **Explanation:** Workers are assigned jobs of difficulty \[4,4,6,6\] and they get a profit of \[20,20,30,30\] separately. **Example 2:** **Input:** difficulty = \[85,47,57\], profit = \[24,66,99\], worker = \[40,25,25\] **Output:** 0 **Constraints:** * `n == difficulty.length` * `n == profit.length` * `m == worker.length` * `1 <= n, m <= 104` * `1 <= difficulty[i], profit[i], worker[i] <= 105`
null
Python3 | Solved Using Binary Search W/ Sorting O((n+m)*logn) Runtime Solution!
most-profit-assigning-work
0
1
```\nclass Solution:\n #Time-Complexity: O(n + nlogn + n + mlog(n)) -> O((n+m) *logn)\n #Space-Complexity: O(n)\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n #Approach: First of all, linearly traverse each and every corresponding index\n #position of first two input arrays: difficulty and profit to group each\n #item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array\n #by increasing difficulty of the job! Then, for each worker, perform binary\n #search and consistently update the max profit the current worker can work and\n #earn! Add this value to answer variable, which is cumulative for all workers!\n #this will be the result returned at the end!\n arr = []\n for i in range(len(difficulty)):\n arr.append([difficulty[i], profit[i]])\n #sort by difficulty!\n arr.sort(key = lambda x: x[0])\n #then, I need to update the maximum profit up to each and every item!\n maximum = float(-inf)\n for j in range(len(arr)):\n maximum = max(maximum, arr[j][1])\n arr[j][1] = maximum\n ans = 0\n #iterate through each and every worker!\n for w in worker:\n bestProfit = 0\n #define search space to perform binary search!\n L, R = 0, len(arr) - 1\n #as long as search space has at least one element to consider or one job,\n #continue iterations of binary search!\n while L <= R:\n mid = (L + R) // 2\n mid_e = arr[mid]\n #check if current job has difficulty that is manageable!\n if(mid_e[0] <= w):\n bestProfit = max(bestProfit, mid_e[1])\n #we still need to search right and try higher difficulty\n #jobs that might yield higher profit!\n L = mid + 1\n continue\n else:\n R = mid - 1\n continue\n #once we break from while loop and end binary search, we should have\n #found bestProfit for current worker performing task that is manageable!\n ans += bestProfit\n return ans
4
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Solution
most-profit-assigning-work
1
1
```C++ []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {\n int n = profit.size(), res = 0, l = 0, p = 0;\n vector<pair<int, int>> pairs;\n for(int i = 0; i < n; i++) pairs.emplace_back(difficulty[i], profit[i]);\n sort(pairs.begin(), pairs.end());\n sort(worker.begin(), worker.end());\n for(int &w: worker){\n while(l < n && w >= pairs[l].first){\n p = max(p, pairs[l++].second);\n }\n res += p;\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n jobs = sorted(zip(profit, difficulty), reverse=True)\n worker.sort()\n total_profit = 0\n\n for prof, diff in jobs:\n while worker and diff <= worker[-1]:\n total_profit += prof\n worker.pop()\n if not worker:\n break\n\n return total_profit\n```\n\n```Java []\nclass Solution {\n public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {\n int max=0;\n for(int d:difficulty)\n max = Math.max(max, d);\n int[] dp = new int[max+1];\n for(int i=0;i<difficulty.length;i++) \n dp[difficulty[i]] = Math.max(dp[difficulty[i]], profit[i]);\n for(int i=1;i<=max;i++)\n dp[i] = Math.max(dp[i-1], dp[i]);\n int ans=0;\n for(int w:worker)\n {\n if(w>max) ans+=dp[max];\n else ans+=dp[w];\n }\n return ans;\n }\n}\n```\n
2
You have `n` jobs and `m` workers. You are given three arrays: `difficulty`, `profit`, and `worker` where: * `difficulty[i]` and `profit[i]` are the difficulty and the profit of the `ith` job, and * `worker[j]` is the ability of `jth` worker (i.e., the `jth` worker can only complete a job with difficulty at most `worker[j]`). Every worker can be assigned **at most one job**, but one job can be **completed multiple times**. * For example, if three workers attempt the same job that pays `$1`, then the total profit will be `$3`. If a worker cannot complete any job, their profit is `$0`. Return the maximum profit we can achieve after assigning the workers to the jobs. **Example 1:** **Input:** difficulty = \[2,4,6,8,10\], profit = \[10,20,30,40,50\], worker = \[4,5,6,7\] **Output:** 100 **Explanation:** Workers are assigned jobs of difficulty \[4,4,6,6\] and they get a profit of \[20,20,30,30\] separately. **Example 2:** **Input:** difficulty = \[85,47,57\], profit = \[24,66,99\], worker = \[40,25,25\] **Output:** 0 **Constraints:** * `n == difficulty.length` * `n == profit.length` * `m == worker.length` * `1 <= n, m <= 104` * `1 <= difficulty[i], profit[i], worker[i] <= 105`
null
Solution
most-profit-assigning-work
1
1
```C++ []\nclass Solution {\npublic:\n int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {\n int n = profit.size(), res = 0, l = 0, p = 0;\n vector<pair<int, int>> pairs;\n for(int i = 0; i < n; i++) pairs.emplace_back(difficulty[i], profit[i]);\n sort(pairs.begin(), pairs.end());\n sort(worker.begin(), worker.end());\n for(int &w: worker){\n while(l < n && w >= pairs[l].first){\n p = max(p, pairs[l++].second);\n }\n res += p;\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n jobs = sorted(zip(profit, difficulty), reverse=True)\n worker.sort()\n total_profit = 0\n\n for prof, diff in jobs:\n while worker and diff <= worker[-1]:\n total_profit += prof\n worker.pop()\n if not worker:\n break\n\n return total_profit\n```\n\n```Java []\nclass Solution {\n public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {\n int max=0;\n for(int d:difficulty)\n max = Math.max(max, d);\n int[] dp = new int[max+1];\n for(int i=0;i<difficulty.length;i++) \n dp[difficulty[i]] = Math.max(dp[difficulty[i]], profit[i]);\n for(int i=1;i<=max;i++)\n dp[i] = Math.max(dp[i-1], dp[i]);\n int ans=0;\n for(int w:worker)\n {\n if(w>max) ans+=dp[max];\n else ans+=dp[w];\n }\n return ans;\n }\n}\n```\n
2
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Python, sorting, bisect
most-profit-assigning-work
0
1
# Intuition\nThe main idea is to get maximum profit for current worker ability.\nFirst of all we need to mix together difficulty and profit, sort them and initialize dp variable with maximum value with at least current difficulty. \n\n# Complexity\n- Time complexity:\nO(N*LogN) for sorting and bisect\n\n- Space complexity:\nO(1)\n\n# Code\n```\nimport bisect\n\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n difficultyProfit = list(zip(difficulty, profit))\n difficultyProfit.sort()\n\n difficulty, profit = zip(*difficultyProfit)\n\n n = len(profit)\n dp = [0] * n\n for i in range(n):\n dp[i] = max(profit[i], dp[i - 1])\n\n result = 0\n for w in worker:\n index = bisect.bisect_right(difficulty, w) - 1\n if index < 0:\n continue\n \n result += dp[index]\n \n return result\n\n\n```
4
You have `n` jobs and `m` workers. You are given three arrays: `difficulty`, `profit`, and `worker` where: * `difficulty[i]` and `profit[i]` are the difficulty and the profit of the `ith` job, and * `worker[j]` is the ability of `jth` worker (i.e., the `jth` worker can only complete a job with difficulty at most `worker[j]`). Every worker can be assigned **at most one job**, but one job can be **completed multiple times**. * For example, if three workers attempt the same job that pays `$1`, then the total profit will be `$3`. If a worker cannot complete any job, their profit is `$0`. Return the maximum profit we can achieve after assigning the workers to the jobs. **Example 1:** **Input:** difficulty = \[2,4,6,8,10\], profit = \[10,20,30,40,50\], worker = \[4,5,6,7\] **Output:** 100 **Explanation:** Workers are assigned jobs of difficulty \[4,4,6,6\] and they get a profit of \[20,20,30,30\] separately. **Example 2:** **Input:** difficulty = \[85,47,57\], profit = \[24,66,99\], worker = \[40,25,25\] **Output:** 0 **Constraints:** * `n == difficulty.length` * `n == profit.length` * `m == worker.length` * `1 <= n, m <= 104` * `1 <= difficulty[i], profit[i], worker[i] <= 105`
null
Python, sorting, bisect
most-profit-assigning-work
0
1
# Intuition\nThe main idea is to get maximum profit for current worker ability.\nFirst of all we need to mix together difficulty and profit, sort them and initialize dp variable with maximum value with at least current difficulty. \n\n# Complexity\n- Time complexity:\nO(N*LogN) for sorting and bisect\n\n- Space complexity:\nO(1)\n\n# Code\n```\nimport bisect\n\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n difficultyProfit = list(zip(difficulty, profit))\n difficultyProfit.sort()\n\n difficulty, profit = zip(*difficultyProfit)\n\n n = len(profit)\n dp = [0] * n\n for i in range(n):\n dp[i] = max(profit[i], dp[i - 1])\n\n result = 0\n for w in worker:\n index = bisect.bisect_right(difficulty, w) - 1\n if index < 0:\n continue\n \n result += dp[index]\n \n return result\n\n\n```
4
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
No Binary Search || Python 3 || EXPLAINEDD
most-profit-assigning-work
0
1
Sort the array on the basis of profit (desc order) instead of difficulty after zipping them togther\nAlso sort the worker array in descending order\nNow if a task difficulty > worker[i] -> this task cant be done by any other worker too so j + 1\nif difficulty < worker[i] => this task can be done i + 1.\n`why not j + 1 here?` Because one task can be done by multiple workers\n# Code\n```\nclass Solution:\n def maxProfitAssignment(self, d: List[int], p: List[int], w: List[int]) -> int:\n task = list(zip(d, p))\n t = sorted(task, key=lambda x:-x[1])\n w.sort(reverse=True)\n profit = 0\n i = 0\n j = 0\n while i < len(w) and j < len(t):\n if w[i] < t[j][0]:\n j += 1\n else:\n profit += t[j][1]\n i += 1 \n return profit\n\n```
2
You have `n` jobs and `m` workers. You are given three arrays: `difficulty`, `profit`, and `worker` where: * `difficulty[i]` and `profit[i]` are the difficulty and the profit of the `ith` job, and * `worker[j]` is the ability of `jth` worker (i.e., the `jth` worker can only complete a job with difficulty at most `worker[j]`). Every worker can be assigned **at most one job**, but one job can be **completed multiple times**. * For example, if three workers attempt the same job that pays `$1`, then the total profit will be `$3`. If a worker cannot complete any job, their profit is `$0`. Return the maximum profit we can achieve after assigning the workers to the jobs. **Example 1:** **Input:** difficulty = \[2,4,6,8,10\], profit = \[10,20,30,40,50\], worker = \[4,5,6,7\] **Output:** 100 **Explanation:** Workers are assigned jobs of difficulty \[4,4,6,6\] and they get a profit of \[20,20,30,30\] separately. **Example 2:** **Input:** difficulty = \[85,47,57\], profit = \[24,66,99\], worker = \[40,25,25\] **Output:** 0 **Constraints:** * `n == difficulty.length` * `n == profit.length` * `m == worker.length` * `1 <= n, m <= 104` * `1 <= difficulty[i], profit[i], worker[i] <= 105`
null
No Binary Search || Python 3 || EXPLAINEDD
most-profit-assigning-work
0
1
Sort the array on the basis of profit (desc order) instead of difficulty after zipping them togther\nAlso sort the worker array in descending order\nNow if a task difficulty > worker[i] -> this task cant be done by any other worker too so j + 1\nif difficulty < worker[i] => this task can be done i + 1.\n`why not j + 1 here?` Because one task can be done by multiple workers\n# Code\n```\nclass Solution:\n def maxProfitAssignment(self, d: List[int], p: List[int], w: List[int]) -> int:\n task = list(zip(d, p))\n t = sorted(task, key=lambda x:-x[1])\n w.sort(reverse=True)\n profit = 0\n i = 0\n j = 0\n while i < len(w) and j < len(t):\n if w[i] < t[j][0]:\n j += 1\n else:\n profit += t[j][1]\n i += 1 \n return profit\n\n```
2
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Python Beginner Friendly Solution || Sorting
most-profit-assigning-work
0
1
# Code\n```\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n temp=[]\n earning=0\n for i in range(len(profit)):\n temp.append([profit[i],difficulty[i]])\n temp.sort()\n temp.reverse()\n for i in worker:\n for j in temp:\n if j[1]<=i:\n earning+=j[0]\n break\n return earning \n```
0
You have `n` jobs and `m` workers. You are given three arrays: `difficulty`, `profit`, and `worker` where: * `difficulty[i]` and `profit[i]` are the difficulty and the profit of the `ith` job, and * `worker[j]` is the ability of `jth` worker (i.e., the `jth` worker can only complete a job with difficulty at most `worker[j]`). Every worker can be assigned **at most one job**, but one job can be **completed multiple times**. * For example, if three workers attempt the same job that pays `$1`, then the total profit will be `$3`. If a worker cannot complete any job, their profit is `$0`. Return the maximum profit we can achieve after assigning the workers to the jobs. **Example 1:** **Input:** difficulty = \[2,4,6,8,10\], profit = \[10,20,30,40,50\], worker = \[4,5,6,7\] **Output:** 100 **Explanation:** Workers are assigned jobs of difficulty \[4,4,6,6\] and they get a profit of \[20,20,30,30\] separately. **Example 2:** **Input:** difficulty = \[85,47,57\], profit = \[24,66,99\], worker = \[40,25,25\] **Output:** 0 **Constraints:** * `n == difficulty.length` * `n == profit.length` * `m == worker.length` * `1 <= n, m <= 104` * `1 <= difficulty[i], profit[i], worker[i] <= 105`
null
Python Beginner Friendly Solution || Sorting
most-profit-assigning-work
0
1
# Code\n```\nclass Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n temp=[]\n earning=0\n for i in range(len(profit)):\n temp.append([profit[i],difficulty[i]])\n temp.sort()\n temp.reverse()\n for i in worker:\n for j in temp:\n if j[1]<=i:\n earning+=j[0]\n break\n return earning \n```
0
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Solution
making-a-large-island
1
1
```C++ []\nauto $$ = [] { return ios::sync_with_stdio(0), cin.tie(0), 0; }();\nint uf[500 * 500];\nint find_(int i) {\n return uf[i] < 0 ? i : uf[i] = find_(uf[i]);\n}\nvoid unite_(int i, int j) {\n i = find_(i), j = find_(j);\n if (i == j) return;\n if (-uf[i] > -uf[j]) swap(i, j);\n uf[j] += uf[i], uf[i] = j;\n}\nconst int dirs[][2] = {0, 1, 1, 0, 0, -1, -1, 0};\nvector<int> ex(4);\n\nclass Solution {\npublic:\n int largestIsland(vector<vector<int>>& grid) {\n int n = grid.size();\n memset(uf, -1, sizeof(uf[0]) * n * n);\n for (int y = 0; y < n; y++) {\n for (int x = 0; x < n; x++) {\n if (!grid[y][x]) continue;\n for (int i : {0, 1}) {\n int ay = y + dirs[i][0], ax = x + dirs[i][1];\n if (ay == n || ax == n) continue;\n if (grid[ay][ax]) unite_(y * n + x, ay * n + ax);\n }\n }\n }\n int ans = 0;\n for (int y = 0; y < n; y++) {\n for (int x = 0; x < n; x++) {\n if (grid[y][x]) {\n ans = max(ans, -uf[find_(y * n + x)]);\n continue;\n }\n int c = 0;\n ex.clear();\n for (auto [dy, dx] : dirs) {\n int ay = y + dy, ax = x + dx;\n if (!~ay || !~ax || ay == n || ax == n) continue;\n if (!grid[ay][ax]) continue;\n int i = find_(ay * n + ax);\n if (find(ex.begin(), ex.end(), i) == ex.end())\n ex.push_back(i);\n }\n for (int i : ex)\n c += -uf[i];\n ans = max(ans, c + 1);\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n rows = len(grid)\n area = 0\n def dfs(r,c,idx):\n grid[r][c] = idx\n nonlocal area\n area += 1\n for dr, dc in [[-1,0],[1,0],[0,-1],[0,1]]:\n nr, nc = r + dr, c + dc\n if nr >= 0 and nr < rows and nc < rows and nc >= 0 and grid[nr][nc] == 1:\n dfs(nr,nc,idx)\n \n label = 2\n hashmap = {}\n\n for r in range(rows):\n for c in range(rows):\n if grid[r][c] == 1:\n area = 0\n dfs(r,c,label)\n hashmap[label] = area\n label += 1\n \n if len(hashmap) == 0: return 1\n _max = max(hashmap.values())\n\n for r in range(rows):\n for c in range(rows):\n if grid[r][c] == 0:\n res = 1\n visit = set()\n for dr, dc in [[-1,0],[1,0],[0,-1],[0,1]]:\n nr, nc = r + dr, c + dc\n if nr >= 0 and nr < rows and nc < rows and nc >= 0 and grid[nr][nc] != 0 and grid[nr][nc] not in visit:\n res += hashmap[grid[nr][nc]]\n visit.add(grid[nr][nc])\n _max = max(_max, res)\n \n return _max\n```\n\n```Java []\nclass Solution {\n public int largestIsland(int[][] grid) {\n int[] componentSizes = new int[grid.length * grid.length + 2];\n int max = 0;\n int id = 2;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid.length; j++) {\n if (grid[i][j] == 1) {\n int[] size = new int[1];\n dfs(grid, componentSizes, id, i, j);\n if(componentSizes[id] > max){\n max = componentSizes[id];\n }\n id++;\n }\n }\n }\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid.length; j++) {\n if (grid[i][j] == 0) {\n max = Math.max(max, getNeighborSum(grid, componentSizes, i, j) + 1);\n }\n }\n }\n return max;\n }\n private void dfs(int[][] grid, int[] componentSizes, int id, int i, int j) {\n if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != 1) return;\n grid[i][j] = id;\n componentSizes[id]++;\n dfs(grid, componentSizes, id, i-1, j);\n dfs(grid, componentSizes, id, i, j-1);\n dfs(grid, componentSizes, id, i+1, j);\n dfs(grid, componentSizes, id, i, j+1);\n }\n private int getNeighborSum(int[][] grid, int[] componentSizes, int i, int j) {\n int[] ids = new int[4];\n int sum = 0;\n if(i-1 >= 0){\n ids[0] = grid[i-1][j];\n }\n if(i+1 < grid.length){\n ids[1] = grid[i+1][j];\n }\n if(j-1 >= 0){\n ids[2] = grid[i][j-1];\n }\n if(j+1 < grid.length){\n ids[3] = grid[i][j+1];\n }\n sum = componentSizes[ids[0]];\n if(ids[1] != ids[0]){\n sum += componentSizes[ids[1]];\n }\n if(ids[2] != ids[0] && ids[2] != ids[1]){\n sum += componentSizes[ids[2]];\n }\n if(ids[3] != ids[0] && ids[3] != ids[1] && ids[3] != ids[2]){\n sum += componentSizes[ids[3]];\n }\n return sum;\n }\n}\n```\n
1
You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. Return _the size of the largest **island** in_ `grid` _after applying this operation_. An **island** is a 4-directionally connected group of `1`s. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** 3 **Explanation:** Change one 0 to 1 and connect two 1s, then we get an island with area = 3. **Example 2:** **Input:** grid = \[\[1,1\],\[1,0\]\] **Output:** 4 **Explanation:** Change the 0 to 1 and make the island bigger, only one island with area = 4. **Example 3:** **Input:** grid = \[\[1,1\],\[1,1\]\] **Output:** 4 **Explanation:** Can't change any 0 to 1, only one island with area = 4. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 500` * `grid[i][j]` is either `0` or `1`.
null
Solution
making-a-large-island
1
1
```C++ []\nauto $$ = [] { return ios::sync_with_stdio(0), cin.tie(0), 0; }();\nint uf[500 * 500];\nint find_(int i) {\n return uf[i] < 0 ? i : uf[i] = find_(uf[i]);\n}\nvoid unite_(int i, int j) {\n i = find_(i), j = find_(j);\n if (i == j) return;\n if (-uf[i] > -uf[j]) swap(i, j);\n uf[j] += uf[i], uf[i] = j;\n}\nconst int dirs[][2] = {0, 1, 1, 0, 0, -1, -1, 0};\nvector<int> ex(4);\n\nclass Solution {\npublic:\n int largestIsland(vector<vector<int>>& grid) {\n int n = grid.size();\n memset(uf, -1, sizeof(uf[0]) * n * n);\n for (int y = 0; y < n; y++) {\n for (int x = 0; x < n; x++) {\n if (!grid[y][x]) continue;\n for (int i : {0, 1}) {\n int ay = y + dirs[i][0], ax = x + dirs[i][1];\n if (ay == n || ax == n) continue;\n if (grid[ay][ax]) unite_(y * n + x, ay * n + ax);\n }\n }\n }\n int ans = 0;\n for (int y = 0; y < n; y++) {\n for (int x = 0; x < n; x++) {\n if (grid[y][x]) {\n ans = max(ans, -uf[find_(y * n + x)]);\n continue;\n }\n int c = 0;\n ex.clear();\n for (auto [dy, dx] : dirs) {\n int ay = y + dy, ax = x + dx;\n if (!~ay || !~ax || ay == n || ax == n) continue;\n if (!grid[ay][ax]) continue;\n int i = find_(ay * n + ax);\n if (find(ex.begin(), ex.end(), i) == ex.end())\n ex.push_back(i);\n }\n for (int i : ex)\n c += -uf[i];\n ans = max(ans, c + 1);\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n rows = len(grid)\n area = 0\n def dfs(r,c,idx):\n grid[r][c] = idx\n nonlocal area\n area += 1\n for dr, dc in [[-1,0],[1,0],[0,-1],[0,1]]:\n nr, nc = r + dr, c + dc\n if nr >= 0 and nr < rows and nc < rows and nc >= 0 and grid[nr][nc] == 1:\n dfs(nr,nc,idx)\n \n label = 2\n hashmap = {}\n\n for r in range(rows):\n for c in range(rows):\n if grid[r][c] == 1:\n area = 0\n dfs(r,c,label)\n hashmap[label] = area\n label += 1\n \n if len(hashmap) == 0: return 1\n _max = max(hashmap.values())\n\n for r in range(rows):\n for c in range(rows):\n if grid[r][c] == 0:\n res = 1\n visit = set()\n for dr, dc in [[-1,0],[1,0],[0,-1],[0,1]]:\n nr, nc = r + dr, c + dc\n if nr >= 0 and nr < rows and nc < rows and nc >= 0 and grid[nr][nc] != 0 and grid[nr][nc] not in visit:\n res += hashmap[grid[nr][nc]]\n visit.add(grid[nr][nc])\n _max = max(_max, res)\n \n return _max\n```\n\n```Java []\nclass Solution {\n public int largestIsland(int[][] grid) {\n int[] componentSizes = new int[grid.length * grid.length + 2];\n int max = 0;\n int id = 2;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid.length; j++) {\n if (grid[i][j] == 1) {\n int[] size = new int[1];\n dfs(grid, componentSizes, id, i, j);\n if(componentSizes[id] > max){\n max = componentSizes[id];\n }\n id++;\n }\n }\n }\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid.length; j++) {\n if (grid[i][j] == 0) {\n max = Math.max(max, getNeighborSum(grid, componentSizes, i, j) + 1);\n }\n }\n }\n return max;\n }\n private void dfs(int[][] grid, int[] componentSizes, int id, int i, int j) {\n if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != 1) return;\n grid[i][j] = id;\n componentSizes[id]++;\n dfs(grid, componentSizes, id, i-1, j);\n dfs(grid, componentSizes, id, i, j-1);\n dfs(grid, componentSizes, id, i+1, j);\n dfs(grid, componentSizes, id, i, j+1);\n }\n private int getNeighborSum(int[][] grid, int[] componentSizes, int i, int j) {\n int[] ids = new int[4];\n int sum = 0;\n if(i-1 >= 0){\n ids[0] = grid[i-1][j];\n }\n if(i+1 < grid.length){\n ids[1] = grid[i+1][j];\n }\n if(j-1 >= 0){\n ids[2] = grid[i][j-1];\n }\n if(j+1 < grid.length){\n ids[3] = grid[i][j+1];\n }\n sum = componentSizes[ids[0]];\n if(ids[1] != ids[0]){\n sum += componentSizes[ids[1]];\n }\n if(ids[2] != ids[0] && ids[2] != ids[1]){\n sum += componentSizes[ids[2]];\n }\n if(ids[3] != ids[0] && ids[3] != ids[1] && ids[3] != ids[2]){\n sum += componentSizes[ids[3]];\n }\n return sum;\n }\n}\n```\n
1
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
DFS based solution, using unique id for each island
making-a-large-island
0
1
\nfirst store all the islands in a list using bfs/dfs\nmark all the islands with a index within the grid\ncreate a hash map with key as index and size of island as the value\nThis will be done by itetrating over teh entire grid once O(m*n)\nwe will have to iterate over the grid again, checking for 0s and flipping\nevery 0 to 1 and see if the size of islands that can be formed. \nWe can do this either by iterating over the grid again (which will result\nin a TLE). So rather, we capture all the water cells in our first iteration \nand then only iterate on the water cells in the next run\n\n```\nclass Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n \n m, n = len(grid), len(grid[0])\n\n def is_valid(i, j):\n return 0 <= i < m and 0 <= j < n\n\n def get_neighbors(i, j):\n return [(i+1,j), (i-1,j), (i,j+1), (i,j-1)]\n\n def dfs(i,j, index):\n grid[i][j] = index\n count = 1\n for nei in get_neighbors(i, j):\n x, y = nei\n if is_valid(x, y) and grid[x][y] == 1:\n grid[x][y] = index\n count+=dfs(x,y, index)\n return count\n\n islands_map = {}\n self.max_len = 0\n water_cells = set()\n\n index = 2\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n water_cells.add((i,j))\n elif grid[i][j] == 1:\n size = dfs(i, j, index)\n islands_map[index] = size\n self.max_len = max(self.max_len, size)\n index+=1\n \n for cell in water_cells:\n i, j = cell\n # make it 1 and see, how big island can be formed idxs = set()\n idxs = set()\n island_len = 1\n for nei in get_neighbors(i, j):\n x, y = nei\n if is_valid(x, y) and grid[x][y] in islands_map and grid[x][y] not in idxs:\n idxs.add(grid[x][y])\n island_len+=islands_map[grid[x][y]]\n\n self.max_len = max(self.max_len, island_len)\n return self.max_len\n```
1
You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. Return _the size of the largest **island** in_ `grid` _after applying this operation_. An **island** is a 4-directionally connected group of `1`s. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** 3 **Explanation:** Change one 0 to 1 and connect two 1s, then we get an island with area = 3. **Example 2:** **Input:** grid = \[\[1,1\],\[1,0\]\] **Output:** 4 **Explanation:** Change the 0 to 1 and make the island bigger, only one island with area = 4. **Example 3:** **Input:** grid = \[\[1,1\],\[1,1\]\] **Output:** 4 **Explanation:** Can't change any 0 to 1, only one island with area = 4. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 500` * `grid[i][j]` is either `0` or `1`.
null
DFS based solution, using unique id for each island
making-a-large-island
0
1
\nfirst store all the islands in a list using bfs/dfs\nmark all the islands with a index within the grid\ncreate a hash map with key as index and size of island as the value\nThis will be done by itetrating over teh entire grid once O(m*n)\nwe will have to iterate over the grid again, checking for 0s and flipping\nevery 0 to 1 and see if the size of islands that can be formed. \nWe can do this either by iterating over the grid again (which will result\nin a TLE). So rather, we capture all the water cells in our first iteration \nand then only iterate on the water cells in the next run\n\n```\nclass Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n \n m, n = len(grid), len(grid[0])\n\n def is_valid(i, j):\n return 0 <= i < m and 0 <= j < n\n\n def get_neighbors(i, j):\n return [(i+1,j), (i-1,j), (i,j+1), (i,j-1)]\n\n def dfs(i,j, index):\n grid[i][j] = index\n count = 1\n for nei in get_neighbors(i, j):\n x, y = nei\n if is_valid(x, y) and grid[x][y] == 1:\n grid[x][y] = index\n count+=dfs(x,y, index)\n return count\n\n islands_map = {}\n self.max_len = 0\n water_cells = set()\n\n index = 2\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n water_cells.add((i,j))\n elif grid[i][j] == 1:\n size = dfs(i, j, index)\n islands_map[index] = size\n self.max_len = max(self.max_len, size)\n index+=1\n \n for cell in water_cells:\n i, j = cell\n # make it 1 and see, how big island can be formed idxs = set()\n idxs = set()\n island_len = 1\n for nei in get_neighbors(i, j):\n x, y = nei\n if is_valid(x, y) and grid[x][y] in islands_map and grid[x][y] not in idxs:\n idxs.add(grid[x][y])\n island_len+=islands_map[grid[x][y]]\n\n self.max_len = max(self.max_len, island_len)\n return self.max_len\n```
1
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
Solution
count-unique-characters-of-all-substrings-of-a-given-string
1
1
```C++ []\nclass Solution {\npublic:\n int uniqueLetterString(string s) {\n int prev_count[26] = {}, prev_position[26];\n for (size_t i = 0; i < 26; ++i) prev_position[i] = -1;\n int result = 0;\n for (int i = 0, count = 0, n = static_cast<int>(s.size()); i < n; ++i)\n {\n int chr_idx = s[i] - \'A\';\n int current = i - std::exchange(prev_position[chr_idx], i);\n count += current - std::exchange(prev_count[chr_idx], current);\n result += count;\n }\n return result;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def uniqueLetterString(self, S):\n index = {c: [-1, -1] for c in ascii_uppercase}\n res = 0\n for i, c in enumerate(S):\n k, j = index[c]\n res += (i - j) * (j - k)\n index[c] = [j, i]\n for c in index:\n k, j = index[c]\n res += (len(S) - j) * (j - k)\n return res % (10**9 + 7)\n```\n\n```Java []\nclass Solution {\n public int uniqueLetterString(String s) {\n int n = s.length();\n int[] right = new int[n];\n int[] left = new int[26];\n Arrays.fill(left , n);\n Arrays.fill(right , n);\n int ans = 0 ;\n for(int i = n - 1; i >= 0 ; i--){\n int curr = s.charAt(i) - \'A\';\n right[i] = left[curr];\n left[curr] = i;\n }\n Arrays.fill(left , -1);\n for(int i = 0 ; i < n ; i++){\n int curr = s.charAt(i) - \'A\';\n int sum = (right[i] - i) * (i - left[curr]);\n ans += sum;\n left[curr] = i;\n }\n return ans;\n }\n}\n```\n
2
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Solution
count-unique-characters-of-all-substrings-of-a-given-string
1
1
```C++ []\nclass Solution {\npublic:\n int uniqueLetterString(string s) {\n int prev_count[26] = {}, prev_position[26];\n for (size_t i = 0; i < 26; ++i) prev_position[i] = -1;\n int result = 0;\n for (int i = 0, count = 0, n = static_cast<int>(s.size()); i < n; ++i)\n {\n int chr_idx = s[i] - \'A\';\n int current = i - std::exchange(prev_position[chr_idx], i);\n count += current - std::exchange(prev_count[chr_idx], current);\n result += count;\n }\n return result;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def uniqueLetterString(self, S):\n index = {c: [-1, -1] for c in ascii_uppercase}\n res = 0\n for i, c in enumerate(S):\n k, j = index[c]\n res += (i - j) * (j - k)\n index[c] = [j, i]\n for c in index:\n k, j = index[c]\n res += (len(S) - j) * (j - k)\n return res % (10**9 + 7)\n```\n\n```Java []\nclass Solution {\n public int uniqueLetterString(String s) {\n int n = s.length();\n int[] right = new int[n];\n int[] left = new int[26];\n Arrays.fill(left , n);\n Arrays.fill(right , n);\n int ans = 0 ;\n for(int i = n - 1; i >= 0 ; i--){\n int curr = s.charAt(i) - \'A\';\n right[i] = left[curr];\n left[curr] = i;\n }\n Arrays.fill(left , -1);\n for(int i = 0 ; i < n ; i++){\n int curr = s.charAt(i) - \'A\';\n int sum = (right[i] - i) * (i - left[curr]);\n ans += sum;\n left[curr] = i;\n }\n return ans;\n }\n}\n```\n
2
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Solution by Python, calculating each char contribution
count-unique-characters-of-all-substrings-of-a-given-string
0
1
# Intuition\nTo calculate each char in string contruibute to final answer\nI learned it from(Chinese Speaking): https://www.youtube.com/watch?v=NngeskF1wsw&t=679s\n# Approach\nsuppose we have many A in string, such that:\n\n```\nB A B B A B A\n i j k\n\n```\nQ: Suppose 3 As have position of i, j, k, how we gonna calculate 2nd A\'s contrubution to final answer?\n\nA: any substring containing jth, but not containing ith and kth would contribute 1. In the other word, any substring in string[i + 1: k] containing jth. \nFurthermore, from i + 1 to j, we have j - i choices, from j to k - 1, we have k - j choice. By simple combinatorics, we have (j - i)(k - j) chooices of substring sttifying above.\n\n\nQ: We now know how to deal with middle A, but what about first A and final A?\n\nA: We make faked A in the begining and end of String, such that\n\n```\n(A) B A B B A B A (A)\n-1 i j k len(s)\n\n```\nSo the A in ith and kth would also be "middle A", and do the calcualting as above\n\n\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution:\n def uniqueLetterString(self, s):\n li = []\n for i in range(26):\n tem = []\n tem.append(-1) # "faked A" in the begining\n li.append(tem)\n for i in range(len(s)):\n # record position of certain char in string\n li[ord(s[i]) - 65].append(i)\n ans = 0\n for each in li:\n each.append(len(s)) # "faked A" in the end\n for i in range(1, len(each) - 1): # We don\'t deal with "faked A"\n ans += ((each[i] - each[i - 1]) * (each[i + 1] - each[i]))\n return ans\n```
1
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Solution by Python, calculating each char contribution
count-unique-characters-of-all-substrings-of-a-given-string
0
1
# Intuition\nTo calculate each char in string contruibute to final answer\nI learned it from(Chinese Speaking): https://www.youtube.com/watch?v=NngeskF1wsw&t=679s\n# Approach\nsuppose we have many A in string, such that:\n\n```\nB A B B A B A\n i j k\n\n```\nQ: Suppose 3 As have position of i, j, k, how we gonna calculate 2nd A\'s contrubution to final answer?\n\nA: any substring containing jth, but not containing ith and kth would contribute 1. In the other word, any substring in string[i + 1: k] containing jth. \nFurthermore, from i + 1 to j, we have j - i choices, from j to k - 1, we have k - j choice. By simple combinatorics, we have (j - i)(k - j) chooices of substring sttifying above.\n\n\nQ: We now know how to deal with middle A, but what about first A and final A?\n\nA: We make faked A in the begining and end of String, such that\n\n```\n(A) B A B B A B A (A)\n-1 i j k len(s)\n\n```\nSo the A in ith and kth would also be "middle A", and do the calcualting as above\n\n\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution:\n def uniqueLetterString(self, s):\n li = []\n for i in range(26):\n tem = []\n tem.append(-1) # "faked A" in the begining\n li.append(tem)\n for i in range(len(s)):\n # record position of certain char in string\n li[ord(s[i]) - 65].append(i)\n ans = 0\n for each in li:\n each.append(len(s)) # "faked A" in the end\n for i in range(1, len(each) - 1): # We don\'t deal with "faked A"\n ans += ((each[i] - each[i - 1]) * (each[i + 1] - each[i]))\n return ans\n```
1
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Python O(n) with intuition / step-by-step thought process
count-unique-characters-of-all-substrings-of-a-given-string
0
1
This is one of my first Hard and I\'m writing in extreme detail to help myself fully understand and internalize this. Even after solving it I have trouble understanding most other solution posts.\n\nIt\'s easiest to understand what this problem actually means with a brute force solution:\n```\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n r=0\n for i in range(len(s)):\n for j in range(i, len(s)):\n ss=s[i:j+1]\n unique=sum([ 1 for (i,v) in Counter(ss).items() if v == 1 ])\n r+=unique\n return r\n```\n(The two loops are generating start and end indices for all possible substrings)\n\nFor every possible substring (for abc meaning a,b,c,ab,bc,abc), we sum the number of characters that appear exactly once in the substring, and return a global sum of sums.\n\nThe problem says s can be up to 10^5 length, and this code is O(n^3), so you can tell we have to do better right away (you can\'t even have a double-for-loop with 10^5 iterations each that does nothing, much less string processing).\n\nOne intuition is, if we can\'t process each substring (which is inherently O(n^3)) maybe we can process each individual character. The key is that for any particular substring, characters don\'t affect each other (like, \'a\' doesn\'t care about how many \'b\' there are). You can kind of see this by reading this horrible solution, which is O(n^3) but even worse:\n```\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n def does_char_appear_once(sub, t):\n num=0\n for c in sub:\n if c==t:\n num+=1\n return num==1\n \n r=0\n for c in string.ascii_uppercase:\n for i in range(len(s)):\n for j in range(i, len(s)):\n if does_char_appear_once(s[i:j+1], c):\n r+=1\n return r\n```\nThe intuition is that while it\'s still processing every substring, the outermost loop means it\'s only looking at one character at a time when it looks at substrings. Understanding that, the next step is, how can we stop processing every substring? Let\'s look at the first example testcase:\n```\nInput: s = "ABC"\nOutput: 10\nExplanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".\nEvery substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10\n```\nThe big logic jump is, "how much does each character contribute to the overall sum"?\nFrom the earlier perspective,\n* "A" contributes 3 because it occurs in three substrings (A,AB,ABC)\n* "B" contributes 4 because it occurs in four substrings (B,AB,BC,ABC)\n* "C" contributes 3 because it occurs in three substrings (C,BC,ABC)\n\nIt\'s pretty simple to see that for \'A\' it contributes 3 because the string is length 3, and all substrings that contain it start at 0.\n\'C\' is the opposite case: it contributes 3 because the string is length 3 and all substrings that contain it end at it.\n\nBut suppose the string is actually \'ABCABC\'. The first \'A\' still only contributes 3 because the next \'A\' is the edge, rather than the end of the string.\nSo far, you can kind of get an idea, let\'s keep track of the index of each character occurrence and add the span between them. \n```\nclass Solution:\n def uniqueLetterString(self, s):\n indices=defaultdict(list)\n for i in range(len(s)):\n indices[s[i]].append(i)\n \n r=0\n for k,v in indices.items():\n for i in range(len(v)):\n if i==0:\n prev=-1\n else:\n prev=v[i-1]\n \n if i==len(v)-1:\n nxt=len(s)\n else:\n nxt=v[i+1]\n \n r+=nxt-prev-1\n return r\n```\nThis works by\n1. Generate a dict mapping each character (A,B,C,...) to the list of indices it occurs.\n2. For each character, add up the span between consecutive occurrences of the same character. It\'s a little trickier because the start and end of string can also act as the boundary, so that\'s the len(s) and -1 defaults. It\'s clear they are the necessary values by considering how A and C can both be satisfied in the "ABC" example.\n\nBut actually, this isn\'t quite right. This works as expected for the first and last character, but for \'B\', it also thinks there are only 3 substrings when there are 4. Why are there 4? A longer example makes this easier to understand:\n\'ABCDEFG\'\nThe contribution of \'A\' and \'G\' make sense and are still correct. But for middle ones such as \'C\' it\'s wrong. Think about the effect of adding another character to the string:\n\'ABCDEFGH\' (added H)\n\'A\' gets one more substring, but to see the problem for \'C\', consider that for each possible ending character to the right of \'C\' (DEFGH), a substring could start at any of \'A\', \'B\', \'C\'. For example, by adding \'H\' we added not just 1 substring, but a substring for each left character:\n\'ABCDEFGH\'\n\'BCDEFGH\'\n\'CDEFGH\'\n\nThis shows there is a multiplicative relationship between left span and right span. Incrementing right_span by 1 adds left_span to the total! Once you understand that, the solution is self-evident: add left_span * right_span, where left_span is the distance to the left to the previous occurence of the character or start of string, and right_span is the same for right side.\nFinal code:\n```\nclass Solution:\n def uniqueLetterString(self, s):\n indices=defaultdict(list)\n for i in range(len(s)):\n indices[s[i]].append(i)\n \n r=0\n for k,v in indices.items():\n for i in range(len(v)):\n curr=v[i]\n if i==0:\n prev=-1\n else:\n prev=v[i-1]\n \n if i==len(v)-1:\n nxt=len(s)\n else:\n nxt=v[i+1]\n \n r+=(curr-prev)*(nxt-curr)\n return r\n```\n\t\t\n\nI think it can be optimized pretty easily to not need O(n) space storing the indices but haven\'t gotten around to trying that.
6
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Python O(n) with intuition / step-by-step thought process
count-unique-characters-of-all-substrings-of-a-given-string
0
1
This is one of my first Hard and I\'m writing in extreme detail to help myself fully understand and internalize this. Even after solving it I have trouble understanding most other solution posts.\n\nIt\'s easiest to understand what this problem actually means with a brute force solution:\n```\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n r=0\n for i in range(len(s)):\n for j in range(i, len(s)):\n ss=s[i:j+1]\n unique=sum([ 1 for (i,v) in Counter(ss).items() if v == 1 ])\n r+=unique\n return r\n```\n(The two loops are generating start and end indices for all possible substrings)\n\nFor every possible substring (for abc meaning a,b,c,ab,bc,abc), we sum the number of characters that appear exactly once in the substring, and return a global sum of sums.\n\nThe problem says s can be up to 10^5 length, and this code is O(n^3), so you can tell we have to do better right away (you can\'t even have a double-for-loop with 10^5 iterations each that does nothing, much less string processing).\n\nOne intuition is, if we can\'t process each substring (which is inherently O(n^3)) maybe we can process each individual character. The key is that for any particular substring, characters don\'t affect each other (like, \'a\' doesn\'t care about how many \'b\' there are). You can kind of see this by reading this horrible solution, which is O(n^3) but even worse:\n```\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n def does_char_appear_once(sub, t):\n num=0\n for c in sub:\n if c==t:\n num+=1\n return num==1\n \n r=0\n for c in string.ascii_uppercase:\n for i in range(len(s)):\n for j in range(i, len(s)):\n if does_char_appear_once(s[i:j+1], c):\n r+=1\n return r\n```\nThe intuition is that while it\'s still processing every substring, the outermost loop means it\'s only looking at one character at a time when it looks at substrings. Understanding that, the next step is, how can we stop processing every substring? Let\'s look at the first example testcase:\n```\nInput: s = "ABC"\nOutput: 10\nExplanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".\nEvery substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10\n```\nThe big logic jump is, "how much does each character contribute to the overall sum"?\nFrom the earlier perspective,\n* "A" contributes 3 because it occurs in three substrings (A,AB,ABC)\n* "B" contributes 4 because it occurs in four substrings (B,AB,BC,ABC)\n* "C" contributes 3 because it occurs in three substrings (C,BC,ABC)\n\nIt\'s pretty simple to see that for \'A\' it contributes 3 because the string is length 3, and all substrings that contain it start at 0.\n\'C\' is the opposite case: it contributes 3 because the string is length 3 and all substrings that contain it end at it.\n\nBut suppose the string is actually \'ABCABC\'. The first \'A\' still only contributes 3 because the next \'A\' is the edge, rather than the end of the string.\nSo far, you can kind of get an idea, let\'s keep track of the index of each character occurrence and add the span between them. \n```\nclass Solution:\n def uniqueLetterString(self, s):\n indices=defaultdict(list)\n for i in range(len(s)):\n indices[s[i]].append(i)\n \n r=0\n for k,v in indices.items():\n for i in range(len(v)):\n if i==0:\n prev=-1\n else:\n prev=v[i-1]\n \n if i==len(v)-1:\n nxt=len(s)\n else:\n nxt=v[i+1]\n \n r+=nxt-prev-1\n return r\n```\nThis works by\n1. Generate a dict mapping each character (A,B,C,...) to the list of indices it occurs.\n2. For each character, add up the span between consecutive occurrences of the same character. It\'s a little trickier because the start and end of string can also act as the boundary, so that\'s the len(s) and -1 defaults. It\'s clear they are the necessary values by considering how A and C can both be satisfied in the "ABC" example.\n\nBut actually, this isn\'t quite right. This works as expected for the first and last character, but for \'B\', it also thinks there are only 3 substrings when there are 4. Why are there 4? A longer example makes this easier to understand:\n\'ABCDEFG\'\nThe contribution of \'A\' and \'G\' make sense and are still correct. But for middle ones such as \'C\' it\'s wrong. Think about the effect of adding another character to the string:\n\'ABCDEFGH\' (added H)\n\'A\' gets one more substring, but to see the problem for \'C\', consider that for each possible ending character to the right of \'C\' (DEFGH), a substring could start at any of \'A\', \'B\', \'C\'. For example, by adding \'H\' we added not just 1 substring, but a substring for each left character:\n\'ABCDEFGH\'\n\'BCDEFGH\'\n\'CDEFGH\'\n\nThis shows there is a multiplicative relationship between left span and right span. Incrementing right_span by 1 adds left_span to the total! Once you understand that, the solution is self-evident: add left_span * right_span, where left_span is the distance to the left to the previous occurence of the character or start of string, and right_span is the same for right side.\nFinal code:\n```\nclass Solution:\n def uniqueLetterString(self, s):\n indices=defaultdict(list)\n for i in range(len(s)):\n indices[s[i]].append(i)\n \n r=0\n for k,v in indices.items():\n for i in range(len(v)):\n curr=v[i]\n if i==0:\n prev=-1\n else:\n prev=v[i-1]\n \n if i==len(v)-1:\n nxt=len(s)\n else:\n nxt=v[i+1]\n \n r+=(curr-prev)*(nxt-curr)\n return r\n```\n\t\t\n\nI think it can be optimized pretty easily to not need O(n) space storing the indices but haven\'t gotten around to trying that.
6
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Python simple O(n)
count-unique-characters-of-all-substrings-of-a-given-string
0
1
\tclass Solution:\n\t\tdef uniqueLetterString(self, s: str) -> int:\n\t\t\tprev = [-1] * len(s)\n\t\t\tnex = [len(s)] * len(s)\n\n\t\t\tindex = {}\n\t\t\tfor i, c in enumerate(s):\n\t\t\t\tif c in index:\n\t\t\t\t\tprev[i] = index[c] \n\t\t\t\tindex[c] = i\n\n\t\t\tindex = {}\n\t\t\tfor i in range(len(s) - 1, -1, -1):\n\t\t\t\tif s[i] in index:\n\t\t\t\t\tnex[i] = index[s[i]]\n\t\t\t\tindex[s[i]] = i\n\n\t\t\tres = 0\n\t\t\tfor i, c in enumerate(s):\n\t\t\t\tres += (nex[i] - i) * (i - prev[i])\n\n\t\t\treturn res
1
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Python simple O(n)
count-unique-characters-of-all-substrings-of-a-given-string
0
1
\tclass Solution:\n\t\tdef uniqueLetterString(self, s: str) -> int:\n\t\t\tprev = [-1] * len(s)\n\t\t\tnex = [len(s)] * len(s)\n\n\t\t\tindex = {}\n\t\t\tfor i, c in enumerate(s):\n\t\t\t\tif c in index:\n\t\t\t\t\tprev[i] = index[c] \n\t\t\t\tindex[c] = i\n\n\t\t\tindex = {}\n\t\t\tfor i in range(len(s) - 1, -1, -1):\n\t\t\t\tif s[i] in index:\n\t\t\t\t\tnex[i] = index[s[i]]\n\t\t\t\tindex[s[i]] = i\n\n\t\t\tres = 0\n\t\t\tfor i, c in enumerate(s):\n\t\t\t\tres += (nex[i] - i) * (i - prev[i])\n\n\t\t\treturn res
1
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Simple Python3 solution O(N) time, O(1) space using defaultdict
count-unique-characters-of-all-substrings-of-a-given-string
0
1
Adapted from [https://leetcode.com/its_dark/](its_dark) solution: https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/129021/O(N)-Java-Solution-DP-Clear-and-easy-to-Understand/265186\n\n```\nfrom collections import defaultdict\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n """\n The key ideas behind the solution:\n 1. The maximum possible substrings that can end at an index are i + 1.\n 2. The contribution of a character to this substring is (i + 1) - it\'s last seen position.\n 3. At each point, sum of all contributions, gives the number of total substrings found so far.\n 4. The last seen position of char is actually i + 1.\n """\n last_position = defaultdict(int) # Used for storing the last position of each character\n contribution = defaultdict(int) # Used for storing the contribution of each character so far. This\n # will possibly be updated throughout the string traversal\n res = 0\n \n for i, char in enumerate(s):\n max_possible_substrs_at_idx = i + 1\n contribution[char] = max_possible_substrs_at_idx - last_position[char]\n \n res+=sum(contribution.values())\n last_position[char] = i + 1\n \n return res\n```
14
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Simple Python3 solution O(N) time, O(1) space using defaultdict
count-unique-characters-of-all-substrings-of-a-given-string
0
1
Adapted from [https://leetcode.com/its_dark/](its_dark) solution: https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/129021/O(N)-Java-Solution-DP-Clear-and-easy-to-Understand/265186\n\n```\nfrom collections import defaultdict\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n """\n The key ideas behind the solution:\n 1. The maximum possible substrings that can end at an index are i + 1.\n 2. The contribution of a character to this substring is (i + 1) - it\'s last seen position.\n 3. At each point, sum of all contributions, gives the number of total substrings found so far.\n 4. The last seen position of char is actually i + 1.\n """\n last_position = defaultdict(int) # Used for storing the last position of each character\n contribution = defaultdict(int) # Used for storing the contribution of each character so far. This\n # will possibly be updated throughout the string traversal\n res = 0\n \n for i, char in enumerate(s):\n max_possible_substrs_at_idx = i + 1\n contribution[char] = max_possible_substrs_at_idx - last_position[char]\n \n res+=sum(contribution.values())\n last_position[char] = i + 1\n \n return res\n```
14
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
python solution | detail explained and easy to understand
count-unique-characters-of-all-substrings-of-a-given-string
0
1
we may need read the problem carefully, if we clearly understand what is this asking for, it will be easy to find out a solution... \nso, "returns the number of unique characters on s", what does this mean? \ne.g.\n```\nIncorrect undersanding:\nSTRING = AAB\nsub-strings\nA -> 1\nA -> 0 already count A, hence 0 here\nB -> 1\nAA -> 1 beucze AA only has 1 unique characotrs A\nAB -> 2\nAAB -> 2 only has A,B tow unique chars\nso, total is 1 + 1 + 1 + 2 + 2 = 7\nbut his this not correct... \n\nSee this correct understanding of this problem:\nAAB \nA -> 1, only 1 unique charactors in this substring, A,\nA -> 1, only 1 unique charactors in this substring, A,\nB -> 1, like above\nAA -> 0, becuze A appeared twice, there\'s no unique charactors here.\nAB -> 2, one A and one B.\nAAB -> 1, AA is not unnique, B is unique here.. \nso, total is 1 + 1 + 1 + 0 + 2 + 1 = 6 \n```\nokay, we are looking for **how many charactors appeared just once** in a substring, like `AAB`, there\'s only one unique charactor `B` apperased once, not **how many unique charactors there** `A` and `B`.\nso, the point of asking here is, \nas a charactors `A`, how many substirng i can be unique in this sub-string...\ne.g.\nstring: M N O P A B B A C D E\n\'A\' as unqie in below 2 sub srings:\nsub-str1: M N O P A B B \nsub-str2: B B A C D E \nuse first substring as an sample:\n1st part: M N O P A -> `A` can be MNOPA, NOPA, OPA, PA, A -> 5 times\n2nd part: B B -> `A` we have 2 extra charactors\nCOMBIN: \nMNOPAB NOPAB OPAB, PAB, AB\nMNOPABB MOPABB OPABB, PABB, ABB \nPlust the oringial ones, then we got the total as 15 times\nso here, easily we find out, for any charactor first, like `A`, and then expand to its left and right, aading those possiblities... \nto above cases. 5 + 5 + 5, or we would see, 5 * 3, \n1st part, we got the 5 possiblities, 2nd part, we have extra 2 charactors for `B`, `BB`, we can always add these 2nd part\'s subsring to the original 5 substrings to be new ones, which is 5 * (2 + 1), 1 here is the orignial 5 substrings. \nso, (4 -(-1)) * (7-4), 4 the 1st A index, 7 the 2nd A index, -1 is the boundary. \nTips:\nwhat is the left or right boundaries? \nIt could be the index of `prev-A` and `next-A`, or the edges of the oringal string 0 and n-1.\nas we are 0 indexed, we can use -1 for 0, n for n-1 \nthe above cases: \nthe first charactors `A` and the last charactors `A` bonundaries:\n`A` index[4, 7] could be change to [-1, 4, 7, 11], \n4-(-1) * (7-4) = 15\n(7-4) * (11-7) = 12\n15 + 12 = 27\n\n```\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n # find all the characotrs\' indexes first\n char_idx = defaultdict(list)\n for i, char in enumerate(s):\n char_idx[char].append(i)\n \n res = 0\n for char in char_idx:\n all_idxs = [-1] + char_idx[char] + [len(s)] # adding boundaries for each charactors\n for i in range(1, len(all_idxs)-1):\n res += (all_idxs[i] - all_idxs[i-1]) * (all_idxs[i+1] - all_idxs[i])\n \n return res\n\n
2
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
python solution | detail explained and easy to understand
count-unique-characters-of-all-substrings-of-a-given-string
0
1
we may need read the problem carefully, if we clearly understand what is this asking for, it will be easy to find out a solution... \nso, "returns the number of unique characters on s", what does this mean? \ne.g.\n```\nIncorrect undersanding:\nSTRING = AAB\nsub-strings\nA -> 1\nA -> 0 already count A, hence 0 here\nB -> 1\nAA -> 1 beucze AA only has 1 unique characotrs A\nAB -> 2\nAAB -> 2 only has A,B tow unique chars\nso, total is 1 + 1 + 1 + 2 + 2 = 7\nbut his this not correct... \n\nSee this correct understanding of this problem:\nAAB \nA -> 1, only 1 unique charactors in this substring, A,\nA -> 1, only 1 unique charactors in this substring, A,\nB -> 1, like above\nAA -> 0, becuze A appeared twice, there\'s no unique charactors here.\nAB -> 2, one A and one B.\nAAB -> 1, AA is not unnique, B is unique here.. \nso, total is 1 + 1 + 1 + 0 + 2 + 1 = 6 \n```\nokay, we are looking for **how many charactors appeared just once** in a substring, like `AAB`, there\'s only one unique charactor `B` apperased once, not **how many unique charactors there** `A` and `B`.\nso, the point of asking here is, \nas a charactors `A`, how many substirng i can be unique in this sub-string...\ne.g.\nstring: M N O P A B B A C D E\n\'A\' as unqie in below 2 sub srings:\nsub-str1: M N O P A B B \nsub-str2: B B A C D E \nuse first substring as an sample:\n1st part: M N O P A -> `A` can be MNOPA, NOPA, OPA, PA, A -> 5 times\n2nd part: B B -> `A` we have 2 extra charactors\nCOMBIN: \nMNOPAB NOPAB OPAB, PAB, AB\nMNOPABB MOPABB OPABB, PABB, ABB \nPlust the oringial ones, then we got the total as 15 times\nso here, easily we find out, for any charactor first, like `A`, and then expand to its left and right, aading those possiblities... \nto above cases. 5 + 5 + 5, or we would see, 5 * 3, \n1st part, we got the 5 possiblities, 2nd part, we have extra 2 charactors for `B`, `BB`, we can always add these 2nd part\'s subsring to the original 5 substrings to be new ones, which is 5 * (2 + 1), 1 here is the orignial 5 substrings. \nso, (4 -(-1)) * (7-4), 4 the 1st A index, 7 the 2nd A index, -1 is the boundary. \nTips:\nwhat is the left or right boundaries? \nIt could be the index of `prev-A` and `next-A`, or the edges of the oringal string 0 and n-1.\nas we are 0 indexed, we can use -1 for 0, n for n-1 \nthe above cases: \nthe first charactors `A` and the last charactors `A` bonundaries:\n`A` index[4, 7] could be change to [-1, 4, 7, 11], \n4-(-1) * (7-4) = 15\n(7-4) * (11-7) = 12\n15 + 12 = 27\n\n```\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n # find all the characotrs\' indexes first\n char_idx = defaultdict(list)\n for i, char in enumerate(s):\n char_idx[char].append(i)\n \n res = 0\n for char in char_idx:\n all_idxs = [-1] + char_idx[char] + [len(s)] # adding boundaries for each charactors\n for i in range(1, len(all_idxs)-1):\n res += (all_idxs[i] - all_idxs[i-1]) * (all_idxs[i+1] - all_idxs[i])\n \n return res\n\n
2
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Python - DP solution O(N)
count-unique-characters-of-all-substrings-of-a-given-string
0
1
"d" stores the last 2 indices of the current letter. "a" stands for the sum of results of all the substrings ending with the current letter "c". \n```\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n d = defaultdict(lambda:(0, 0))\n res = a = 0\n for i, c in enumerate(s, 1):\n a += i - 2 * (d[c][1] - d[c][0]) - d[c][0]\n res += a\n d[c] = (d[c][1], i)\n return res\n```
7
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Python - DP solution O(N)
count-unique-characters-of-all-substrings-of-a-given-string
0
1
"d" stores the last 2 indices of the current letter. "a" stands for the sum of results of all the substrings ending with the current letter "c". \n```\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n d = defaultdict(lambda:(0, 0))\n res = a = 0\n for i, c in enumerate(s, 1):\n a += i - 2 * (d[c][1] - d[c][0]) - d[c][0]\n res += a\n d[c] = (d[c][1], i)\n return res\n```
7
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Solution
consecutive-numbers-sum
1
1
```C++ []\nclass Solution {\npublic:\n int consecutiveNumbersSum(int n) {\n int ans=1;\n for(int i=2;i<n;i++) {\n if((i*(i+1))/2 > n) return ans;\n if((n - (i*(i+1))/2)%i==0) ans++;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n res, i = 1, 3\n while n % 2 == 0:\n n //= 2\n \n while i*i <= n:\n count = 0\n while n % i == 0:\n n //= i\n count += 1\n res *= count + 1\n i += 2\n return res if n == 1 else res * 2\n```\n\n```Java []\nclass Solution {\n public int consecutiveNumbersSum(int N) {\n int res = 1, count;\n while (N % 2 == 0) N /= 2;\n for (int i = 3; i * i <= N; i += 2) {\n count = 0;\n while (N % i == 0) {\n N /= i;\n count++;\n }\n res *= count + 1;\n }\n return N == 1 ? res : res * 2;\n }\n}\n```\n
1
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._ **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** 5 = 2 + 3 **Example 2:** **Input:** n = 9 **Output:** 3 **Explanation:** 9 = 4 + 5 = 2 + 3 + 4 **Example 3:** **Input:** n = 15 **Output:** 4 **Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 **Constraints:** * `1 <= n <= 109`
null
Solution
consecutive-numbers-sum
1
1
```C++ []\nclass Solution {\npublic:\n int consecutiveNumbersSum(int n) {\n int ans=1;\n for(int i=2;i<n;i++) {\n if((i*(i+1))/2 > n) return ans;\n if((n - (i*(i+1))/2)%i==0) ans++;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n res, i = 1, 3\n while n % 2 == 0:\n n //= 2\n \n while i*i <= n:\n count = 0\n while n % i == 0:\n n //= i\n count += 1\n res *= count + 1\n i += 2\n return res if n == 1 else res * 2\n```\n\n```Java []\nclass Solution {\n public int consecutiveNumbersSum(int N) {\n int res = 1, count;\n while (N % 2 == 0) N /= 2;\n for (int i = 3; i * i <= N; i += 2) {\n count = 0;\n while (N % i == 0) {\n N /= i;\n count++;\n }\n res *= count + 1;\n }\n return N == 1 ? res : res * 2;\n }\n}\n```\n
1
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced parentheses string. **Example 1:** **Input:** s = "() " **Output:** 1 **Example 2:** **Input:** s = "(()) " **Output:** 2 **Example 3:** **Input:** s = "()() " **Output:** 2 **Constraints:** * `2 <= s.length <= 50` * `s` consists of only `'('` and `')'`. * `s` is a balanced parentheses string.
null
✔️ PYTHON || EXPLAINED || ;]
consecutive-numbers-sum
0
1
**UPVOTE IF HELPFuuL**\nFirstly the question demands sum of consecutive ```positive``` integers.\n\nLet there be ```k``` positive integers that sum to ```num```.\n\n**Only possible values of k are ```1 <= k <= \u221A( 2*num )```**\n\nBecause sum of first k ```positive``` numbers is **( k * ( k+1 ) ) / 2**\n\nHence our search space is reduced.\n\nNow for odd values of k.\n* It is valid if and only if **num % k == 0**.\n* Proof is divide the number to get the middle of consecutive numbers, and form arithmetic progression with diff +1 and -1\n\nFor even values,\nTest runs are needed to be done.\n* for k=2, sum = n + n+1 = **2y + 1**\n* for k=4, sum = n + n+1 + n+2 + n+3 = 4y+6 = **4x +2**\n* same way for k=6, sum = **6x+3**\n* for k=8 , sum = **8x+4**\n\n* Hence for ```k = i``` and i is even, \nSum will exist if ```( i * x ) + ( i / 2 ) == num```\nOR we can say ``` ( num - ( i / 2 )) % ( i ) ==0\nIf above condition hold then a **x** exists\n\n**UPVOTE IF HELPFuuL**\n\n```\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n i=1\n res=0\n k=int((n*2)**0.5)\n while i<=k:\n if i%2:\n if n%i==0:\n res+=1\n elif (n-(i//2))%i==0:\n res+=1\n i+=1\n return res\n```\n\n![image](https://assets.leetcode.com/users/images/f53fe2c0-978c-4939-baa5-5d30cec472ab_1655201159.264783.jpeg)\n
5
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._ **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** 5 = 2 + 3 **Example 2:** **Input:** n = 9 **Output:** 3 **Explanation:** 9 = 4 + 5 = 2 + 3 + 4 **Example 3:** **Input:** n = 15 **Output:** 4 **Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 **Constraints:** * `1 <= n <= 109`
null
✔️ PYTHON || EXPLAINED || ;]
consecutive-numbers-sum
0
1
**UPVOTE IF HELPFuuL**\nFirstly the question demands sum of consecutive ```positive``` integers.\n\nLet there be ```k``` positive integers that sum to ```num```.\n\n**Only possible values of k are ```1 <= k <= \u221A( 2*num )```**\n\nBecause sum of first k ```positive``` numbers is **( k * ( k+1 ) ) / 2**\n\nHence our search space is reduced.\n\nNow for odd values of k.\n* It is valid if and only if **num % k == 0**.\n* Proof is divide the number to get the middle of consecutive numbers, and form arithmetic progression with diff +1 and -1\n\nFor even values,\nTest runs are needed to be done.\n* for k=2, sum = n + n+1 = **2y + 1**\n* for k=4, sum = n + n+1 + n+2 + n+3 = 4y+6 = **4x +2**\n* same way for k=6, sum = **6x+3**\n* for k=8 , sum = **8x+4**\n\n* Hence for ```k = i``` and i is even, \nSum will exist if ```( i * x ) + ( i / 2 ) == num```\nOR we can say ``` ( num - ( i / 2 )) % ( i ) ==0\nIf above condition hold then a **x** exists\n\n**UPVOTE IF HELPFuuL**\n\n```\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n i=1\n res=0\n k=int((n*2)**0.5)\n while i<=k:\n if i%2:\n if n%i==0:\n res+=1\n elif (n-(i//2))%i==0:\n res+=1\n i+=1\n return res\n```\n\n![image](https://assets.leetcode.com/users/images/f53fe2c0-978c-4939-baa5-5d30cec472ab_1655201159.264783.jpeg)\n
5
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced parentheses string. **Example 1:** **Input:** s = "() " **Output:** 1 **Example 2:** **Input:** s = "(()) " **Output:** 2 **Example 3:** **Input:** s = "()() " **Output:** 2 **Constraints:** * `2 <= s.length <= 50` * `s` consists of only `'('` and `')'`. * `s` is a balanced parentheses string.
null
[Python] Quick maths (slightly different from other solns)
consecutive-numbers-sum
0
1
If n can be written as the sum of consecutive integers, say from y+1, y+2, ..., x, then it is also the difference between the sum of the first x positive integers and the first y positive integers. Thus, we can write\nn = x(x+1)/2-y(y+1)/2<=>\n8n = 4x^2+4x+1-(4y^2+4y+1)<=>\n8n =(2x+1)^2 - (2y+1)^2<=>\n8n = (2x-2y)(2x+2y+2)<=>\n2n = (x-y)(x+y+1)\nThe main observation is now that x-y, x+y+1 have different parities, since they differ by 2y+1 which is an odd number.\n\nThus, we get a solution (x,y) corresponding to each pair of divisors of different parities of 2n. It suffices then to cycle through all i from 1 to floor of root(2n) and check whether \na) i divides 2n\nb) whether 2n/i and i have the same parity\n\ncode included for completion:\n```\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n count = 0\n k = floor(math.sqrt(2*n))\n for i in range(1,k+1):\n if (2*n)%i==0 and (2*n/i+i)%2!=0:\n count +=1\n \n return count\n```
1
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._ **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** 5 = 2 + 3 **Example 2:** **Input:** n = 9 **Output:** 3 **Explanation:** 9 = 4 + 5 = 2 + 3 + 4 **Example 3:** **Input:** n = 15 **Output:** 4 **Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 **Constraints:** * `1 <= n <= 109`
null
[Python] Quick maths (slightly different from other solns)
consecutive-numbers-sum
0
1
If n can be written as the sum of consecutive integers, say from y+1, y+2, ..., x, then it is also the difference between the sum of the first x positive integers and the first y positive integers. Thus, we can write\nn = x(x+1)/2-y(y+1)/2<=>\n8n = 4x^2+4x+1-(4y^2+4y+1)<=>\n8n =(2x+1)^2 - (2y+1)^2<=>\n8n = (2x-2y)(2x+2y+2)<=>\n2n = (x-y)(x+y+1)\nThe main observation is now that x-y, x+y+1 have different parities, since they differ by 2y+1 which is an odd number.\n\nThus, we get a solution (x,y) corresponding to each pair of divisors of different parities of 2n. It suffices then to cycle through all i from 1 to floor of root(2n) and check whether \na) i divides 2n\nb) whether 2n/i and i have the same parity\n\ncode included for completion:\n```\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n count = 0\n k = floor(math.sqrt(2*n))\n for i in range(1,k+1):\n if (2*n)%i==0 and (2*n/i+i)%2!=0:\n count +=1\n \n return count\n```
1
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced parentheses string. **Example 1:** **Input:** s = "() " **Output:** 1 **Example 2:** **Input:** s = "(()) " **Output:** 2 **Example 3:** **Input:** s = "()() " **Output:** 2 **Constraints:** * `2 <= s.length <= 50` * `s` consists of only `'('` and `')'`. * `s` is a balanced parentheses string.
null
8 lines Python3 code
consecutive-numbers-sum
0
1
Let say integer **n** is equal to sum of **i** consecutive positive integers. Then \n**n=a+(a+1)+(a+2)..+(a+i-1)**\n**=ai+(0+1+2+...+(i-1))**\nso **(n-(0+1+2+...+(i-1)))/i==a**, which means if **(n-(0+1+2+...+(i-1))) % i ==0**, there will be integer **a** and **i** satisfies the requirement.\n\n\n\n```\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n csum=0\n result=0\n for i in range(1,n+1):\n csum+=i-1\n if csum>=n:\n break\n if (n-csum)%i==0:\n result+=1\n return result\n```
7
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._ **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** 5 = 2 + 3 **Example 2:** **Input:** n = 9 **Output:** 3 **Explanation:** 9 = 4 + 5 = 2 + 3 + 4 **Example 3:** **Input:** n = 15 **Output:** 4 **Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 **Constraints:** * `1 <= n <= 109`
null
8 lines Python3 code
consecutive-numbers-sum
0
1
Let say integer **n** is equal to sum of **i** consecutive positive integers. Then \n**n=a+(a+1)+(a+2)..+(a+i-1)**\n**=ai+(0+1+2+...+(i-1))**\nso **(n-(0+1+2+...+(i-1)))/i==a**, which means if **(n-(0+1+2+...+(i-1))) % i ==0**, there will be integer **a** and **i** satisfies the requirement.\n\n\n\n```\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n csum=0\n result=0\n for i in range(1,n+1):\n csum+=i-1\n if csum>=n:\n break\n if (n-csum)%i==0:\n result+=1\n return result\n```
7
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced parentheses string. **Example 1:** **Input:** s = "() " **Output:** 1 **Example 2:** **Input:** s = "(()) " **Output:** 2 **Example 3:** **Input:** s = "()() " **Output:** 2 **Constraints:** * `2 <= s.length <= 50` * `s` consists of only `'('` and `')'`. * `s` is a balanced parentheses string.
null
Solution
positions-of-large-groups
1
1
```C++ []\nclass Solution {\npublic:\n vector<vector<int>> largeGroupPositions(string s) {\n vector<vector<int>> ans;\n int start = 0, n = s.length(), end;\n for (end = 0; end < n; ++end) {\n if (s[end] != s[start]) {\n if (end-start >= 3) {\n ans.push_back({start, end-1});\n }\n start = end;\n }\n }\n if (end-start >= 3) {\n ans.push_back({start, end-1});\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n count = 0\n prev = None\n intervals = []\n s = s + str(ord(s[-1]) + 1)\n for i, c in enumerate(s):\n if c != prev:\n if count >= 3:\n intervals.append([i - count, i - 1])\n count = 1\n else:\n count += 1\n prev = c\n return intervals\n```\n\n```Java []\nclass Solution {\n public List<List<Integer>> largeGroupPositions(String s) {\n List<List<Integer>> resultList = new ArrayList<>();\n int pointer = 0;\n int length = s.length();\n while(pointer < length) {\n char character = s.charAt(pointer);\n int j = pointer;\n while(j < length && s.charAt(j) == s.charAt(pointer)) {\n j++;\n }\n if (j - pointer >= 3) {\n List<Integer> indexs = new ArrayList<>();\n indexs.add(pointer);\n indexs.add(j - 1);\n resultList.add(indexs);\n }\n pointer = j;\n }\n return resultList;\n }\n}\n```\n
2
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Solution
positions-of-large-groups
1
1
```C++ []\nclass Solution {\npublic:\n vector<vector<int>> largeGroupPositions(string s) {\n vector<vector<int>> ans;\n int start = 0, n = s.length(), end;\n for (end = 0; end < n; ++end) {\n if (s[end] != s[start]) {\n if (end-start >= 3) {\n ans.push_back({start, end-1});\n }\n start = end;\n }\n }\n if (end-start >= 3) {\n ans.push_back({start, end-1});\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n count = 0\n prev = None\n intervals = []\n s = s + str(ord(s[-1]) + 1)\n for i, c in enumerate(s):\n if c != prev:\n if count >= 3:\n intervals.append([i - count, i - 1])\n count = 1\n else:\n count += 1\n prev = c\n return intervals\n```\n\n```Java []\nclass Solution {\n public List<List<Integer>> largeGroupPositions(String s) {\n List<List<Integer>> resultList = new ArrayList<>();\n int pointer = 0;\n int length = s.length();\n while(pointer < length) {\n char character = s.charAt(pointer);\n int j = pointer;\n while(j < length && s.charAt(j) == s.charAt(pointer)) {\n j++;\n }\n if (j - pointer >= 3) {\n List<Integer> indexs = new ArrayList<>();\n indexs.add(pointer);\n indexs.add(j - 1);\n resultList.add(indexs);\n }\n pointer = j;\n }\n return resultList;\n }\n}\n```\n
2
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to the following rules: 1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. 2. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer `k`, return _the least amount of money needed to form a paid group satisfying the above conditions_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** quality = \[10,20,5\], wage = \[70,50,30\], k = 2 **Output:** 105.00000 **Explanation:** We pay 70 to 0th worker and 35 to 2nd worker. **Example 2:** **Input:** quality = \[3,1,10,10,1\], wage = \[4,8,2,2,7\], k = 3 **Output:** 30.66667 **Explanation:** We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. **Constraints:** * `n == quality.length == wage.length` * `1 <= k <= n <= 104` * `1 <= quality[i], wage[i] <= 104`
null
Python Two Pointer - O(n) - Time Complexity in Top 92 %
positions-of-large-groups
0
1
```\nclass Solution:\n def largeGroupPositions(self, S: str) -> List[List[int]]:\n left = 0 \n return_list = []\n S += \'1\'\n for index, letter in enumerate(S):\n if letter != S[left]:\n if index - left >= 3:\n return_list.append([left, index - 1])\n left = index\n return return_list\n```
11
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Python Two Pointer - O(n) - Time Complexity in Top 92 %
positions-of-large-groups
0
1
```\nclass Solution:\n def largeGroupPositions(self, S: str) -> List[List[int]]:\n left = 0 \n return_list = []\n S += \'1\'\n for index, letter in enumerate(S):\n if letter != S[left]:\n if index - left >= 3:\n return_list.append([left, index - 1])\n left = index\n return return_list\n```
11
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to the following rules: 1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. 2. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer `k`, return _the least amount of money needed to form a paid group satisfying the above conditions_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** quality = \[10,20,5\], wage = \[70,50,30\], k = 2 **Output:** 105.00000 **Explanation:** We pay 70 to 0th worker and 35 to 2nd worker. **Example 2:** **Input:** quality = \[3,1,10,10,1\], wage = \[4,8,2,2,7\], k = 3 **Output:** 30.66667 **Explanation:** We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. **Constraints:** * `n == quality.length == wage.length` * `1 <= k <= n <= 104` * `1 <= quality[i], wage[i] <= 104`
null
Straight forward solutions
positions-of-large-groups
0
1
# Code\n```\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n n = len(s)\n if n < 3:\n return ""\n \n temp, prev, cnt = [[0, 0]], s[0], 1\n for k, char in enumerate(s[1:]):\n if prev == char:\n cnt += 1\n else:\n cnt += 1\n if cnt >= 3:\n temp[-1][-1] = k\n \n cnt = 1\n temp += [[k+1, k+2]]\n\n prev = char\n \n temp[-1][-1] = n-1\n\n ret = []\n for v in temp:\n a, b = v\n if b - a >= 2:\n ret += [[a, b]]\n\n return ret\n\n```
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Straight forward solutions
positions-of-large-groups
0
1
# Code\n```\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n n = len(s)\n if n < 3:\n return ""\n \n temp, prev, cnt = [[0, 0]], s[0], 1\n for k, char in enumerate(s[1:]):\n if prev == char:\n cnt += 1\n else:\n cnt += 1\n if cnt >= 3:\n temp[-1][-1] = k\n \n cnt = 1\n temp += [[k+1, k+2]]\n\n prev = char\n \n temp[-1][-1] = n-1\n\n ret = []\n for v in temp:\n a, b = v\n if b - a >= 2:\n ret += [[a, b]]\n\n return ret\n\n```
0
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to the following rules: 1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. 2. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer `k`, return _the least amount of money needed to form a paid group satisfying the above conditions_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** quality = \[10,20,5\], wage = \[70,50,30\], k = 2 **Output:** 105.00000 **Explanation:** We pay 70 to 0th worker and 35 to 2nd worker. **Example 2:** **Input:** quality = \[3,1,10,10,1\], wage = \[4,8,2,2,7\], k = 3 **Output:** 30.66667 **Explanation:** We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. **Constraints:** * `n == quality.length == wage.length` * `1 <= k <= n <= 104` * `1 <= quality[i], wage[i] <= 104`
null
Simple Python3 solution w/ for loops
positions-of-large-groups
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)$$ -->\n\n# Code\n```\n# Constraints\nMIN = 1\nMAX = 1000\n\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n # Checks if string lenght is within constraints\n if (len(s) < MIN or len(s) > MAX) or (s.isalpha() == False or s.islower() == False):\n return []\n \n large_groups = []\n group = []\n\n # Iterates through the indexes and characters of the string\n for index, char in enumerate(s):\n # Checks if group isn\'t null, and if its at the end of a group pattern\n if group != [] and char != s[index - 1]:\n # Checks if group lenght is valid\n if len(group) >= 3:\n # Adds the start index and end index of the last group pattern\n large_groups.append([group[0], group[-1]])\n group.clear()\n group.append(index)\n # Checks if there were \'forgotten\' group (in case the string ends, but there is a valid group)\n if group != [] and len(group) >= 3:\n large_groups.append([group[0], group[-1]])\n return large_groups\n\n\n```
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Simple Python3 solution w/ for loops
positions-of-large-groups
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)$$ -->\n\n# Code\n```\n# Constraints\nMIN = 1\nMAX = 1000\n\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n # Checks if string lenght is within constraints\n if (len(s) < MIN or len(s) > MAX) or (s.isalpha() == False or s.islower() == False):\n return []\n \n large_groups = []\n group = []\n\n # Iterates through the indexes and characters of the string\n for index, char in enumerate(s):\n # Checks if group isn\'t null, and if its at the end of a group pattern\n if group != [] and char != s[index - 1]:\n # Checks if group lenght is valid\n if len(group) >= 3:\n # Adds the start index and end index of the last group pattern\n large_groups.append([group[0], group[-1]])\n group.clear()\n group.append(index)\n # Checks if there were \'forgotten\' group (in case the string ends, but there is a valid group)\n if group != [] and len(group) >= 3:\n large_groups.append([group[0], group[-1]])\n return large_groups\n\n\n```
0
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to the following rules: 1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. 2. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer `k`, return _the least amount of money needed to form a paid group satisfying the above conditions_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** quality = \[10,20,5\], wage = \[70,50,30\], k = 2 **Output:** 105.00000 **Explanation:** We pay 70 to 0th worker and 35 to 2nd worker. **Example 2:** **Input:** quality = \[3,1,10,10,1\], wage = \[4,8,2,2,7\], k = 3 **Output:** 30.66667 **Explanation:** We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. **Constraints:** * `n == quality.length == wage.length` * `1 <= k <= n <= 104` * `1 <= quality[i], wage[i] <= 104`
null
Python easy solution
positions-of-large-groups
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing start, end, temp and prev variable and then just iterate through loop in s.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n prev = s[0]\n tmp = s[0]\n res = []\n start = 0\n end = 0\n for i in range(1, len(s)):\n if s[i] == prev:\n tmp += s[i]\n end = i\n else:\n if len(tmp) >= 3:\n res.append([start, end])\n tmp = s[i]\n prev = s[i]\n start = i\n end = i\n \n if len(tmp) >= 3:\n res.append([start, end])\n return res\n\n \n```
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Python easy solution
positions-of-large-groups
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing start, end, temp and prev variable and then just iterate through loop in s.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n prev = s[0]\n tmp = s[0]\n res = []\n start = 0\n end = 0\n for i in range(1, len(s)):\n if s[i] == prev:\n tmp += s[i]\n end = i\n else:\n if len(tmp) >= 3:\n res.append([start, end])\n tmp = s[i]\n prev = s[i]\n start = i\n end = i\n \n if len(tmp) >= 3:\n res.append([start, end])\n return res\n\n \n```
0
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to the following rules: 1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. 2. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer `k`, return _the least amount of money needed to form a paid group satisfying the above conditions_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** quality = \[10,20,5\], wage = \[70,50,30\], k = 2 **Output:** 105.00000 **Explanation:** We pay 70 to 0th worker and 35 to 2nd worker. **Example 2:** **Input:** quality = \[3,1,10,10,1\], wage = \[4,8,2,2,7\], k = 3 **Output:** 30.66667 **Explanation:** We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. **Constraints:** * `n == quality.length == wage.length` * `1 <= k <= n <= 104` * `1 <= quality[i], wage[i] <= 104`
null
Simple Python3 Solution || Upto 100 % Faster
positions-of-large-groups
0
1
\n![image.png](https://assets.leetcode.com/users/images/986e9196-2b4d-41b2-85cb-dce19d6738bc_1696501712.3068585.png)\n\n# Complexity\n- Time complexity:\nO(2n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n if len(set(s)) == 1:\n if len(s) > 2:\n return [[0,len(s)-1]]\n else:\n return []\n st = []\n\n\n for i in range(1,len(s)):\n if s[i] != s[i-1]:\n st.append(i)\n\n if st[-1] < len(s)-2:\n st.append(len(s))\n \n #print(st)\n\n res = [] \n pre = 0 \n for i in range(len(st)):\n if st[i] - pre >2:\n res.append([pre,st[i]-1])\n pre = st[i]\n return res\n \n```
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Simple Python3 Solution || Upto 100 % Faster
positions-of-large-groups
0
1
\n![image.png](https://assets.leetcode.com/users/images/986e9196-2b4d-41b2-85cb-dce19d6738bc_1696501712.3068585.png)\n\n# Complexity\n- Time complexity:\nO(2n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n if len(set(s)) == 1:\n if len(s) > 2:\n return [[0,len(s)-1]]\n else:\n return []\n st = []\n\n\n for i in range(1,len(s)):\n if s[i] != s[i-1]:\n st.append(i)\n\n if st[-1] < len(s)-2:\n st.append(len(s))\n \n #print(st)\n\n res = [] \n pre = 0 \n for i in range(len(st)):\n if st[i] - pre >2:\n res.append([pre,st[i]-1])\n pre = st[i]\n return res\n \n```
0
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to the following rules: 1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. 2. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer `k`, return _the least amount of money needed to form a paid group satisfying the above conditions_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** quality = \[10,20,5\], wage = \[70,50,30\], k = 2 **Output:** 105.00000 **Explanation:** We pay 70 to 0th worker and 35 to 2nd worker. **Example 2:** **Input:** quality = \[3,1,10,10,1\], wage = \[4,8,2,2,7\], k = 3 **Output:** 30.66667 **Explanation:** We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. **Constraints:** * `n == quality.length == wage.length` * `1 <= k <= n <= 104` * `1 <= quality[i], wage[i] <= 104`
null
Solution
masking-personal-information
1
1
```C++ []\nclass Solution {\npublic:\n string maskPII(string S) {\n auto at = S.find("@");\n if (at != string::npos) {\n transform(S.begin(), S.end(), S.begin(), ::tolower);\n return S.substr(0, 1) + "*****" + S.substr(at - 1);\n }\n string digits;\n for (const auto& c : S) {\n if (::isdigit(c)) {\n digits.push_back(c);\n }\n }\n string local{"***-***-"};\n local += digits.substr(digits.length() - 4);\n if (digits.length() == 10) {\n return local;\n }\n return "+" + string(digits.length() - 10, \'*\') + "-" + local;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maskPII(self, s: str) -> str:\n if \'@\' in s:\n s = s.lower()\n ss = s.split(\'@\')\n return ss[0][0] + \'*****\' + ss[0][-1] + \'@\' + ss[1]\n \n k = len([int(x) for x in s if x.isdigit()]) - 10\n res, local_num = \'+\' + \'*\'*k + \'-\' if k > 0 else \'\', \'\' \n idx = -1\n while len(local_num) < 4:\n if (ch := s[idx]).isdigit():\n local_num += ch\n idx -= 1\n res += \'***-***-\' + local_num[::-1]\n\n return res\n```\n\n```Java []\nclass Solution {\n public String maskPII(String s) {\n boolean flag = s.contains("@");\n if (flag) {\n String[] strs = s.split("@");\n StringBuilder sb = new StringBuilder();\n sb.append(Character.toLowerCase(strs[0].charAt(0)));\n sb.append("*****");\n sb.append(Character.toLowerCase(strs[0].charAt(strs[0].length() - 1)));\n sb.append("@");\n for (char c : strs[1].toCharArray()) {\n if (c == \'.\') {\n sb.append(c);\n } else {\n sb.append(Character.toLowerCase(c));\n }\n }\n return sb.toString();\n } else {\n StringBuilder sb = new StringBuilder();\n for (char c : s.toCharArray()) {\n if (Character.isDigit(c)) {\n sb.append(c);\n }\n }\n int len = sb.length();\n sb.delete(0, sb.length() - 4);\n sb.insert(0, "***-***-");\n if (len == 10) {\n return sb.toString();\n } else {\n sb.insert(0, "-");\n for (int i = 0; i < len - 10; i++) {\n sb.insert(0, "*");\n }\n sb.insert(0, "+");\n return sb.toString();\n }\n }\n }\n}\n```\n
1
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
Solution
masking-personal-information
1
1
```C++ []\nclass Solution {\npublic:\n string maskPII(string S) {\n auto at = S.find("@");\n if (at != string::npos) {\n transform(S.begin(), S.end(), S.begin(), ::tolower);\n return S.substr(0, 1) + "*****" + S.substr(at - 1);\n }\n string digits;\n for (const auto& c : S) {\n if (::isdigit(c)) {\n digits.push_back(c);\n }\n }\n string local{"***-***-"};\n local += digits.substr(digits.length() - 4);\n if (digits.length() == 10) {\n return local;\n }\n return "+" + string(digits.length() - 10, \'*\') + "-" + local;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maskPII(self, s: str) -> str:\n if \'@\' in s:\n s = s.lower()\n ss = s.split(\'@\')\n return ss[0][0] + \'*****\' + ss[0][-1] + \'@\' + ss[1]\n \n k = len([int(x) for x in s if x.isdigit()]) - 10\n res, local_num = \'+\' + \'*\'*k + \'-\' if k > 0 else \'\', \'\' \n idx = -1\n while len(local_num) < 4:\n if (ch := s[idx]).isdigit():\n local_num += ch\n idx -= 1\n res += \'***-***-\' + local_num[::-1]\n\n return res\n```\n\n```Java []\nclass Solution {\n public String maskPII(String s) {\n boolean flag = s.contains("@");\n if (flag) {\n String[] strs = s.split("@");\n StringBuilder sb = new StringBuilder();\n sb.append(Character.toLowerCase(strs[0].charAt(0)));\n sb.append("*****");\n sb.append(Character.toLowerCase(strs[0].charAt(strs[0].length() - 1)));\n sb.append("@");\n for (char c : strs[1].toCharArray()) {\n if (c == \'.\') {\n sb.append(c);\n } else {\n sb.append(Character.toLowerCase(c));\n }\n }\n return sb.toString();\n } else {\n StringBuilder sb = new StringBuilder();\n for (char c : s.toCharArray()) {\n if (Character.isDigit(c)) {\n sb.append(c);\n }\n }\n int len = sb.length();\n sb.delete(0, sb.length() - 4);\n sb.insert(0, "***-***-");\n if (len == 10) {\n return sb.toString();\n } else {\n sb.insert(0, "-");\n for (int i = 0; i < len - 10; i++) {\n sb.insert(0, "*");\n }\n sb.insert(0, "+");\n return sb.toString();\n }\n }\n }\n}\n```\n
1
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor. Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_. The test cases are guaranteed so that the ray will meet a receptor eventually. **Example 1:** **Input:** p = 2, q = 1 **Output:** 2 **Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall. **Example 2:** **Input:** p = 3, q = 1 **Output:** 1 **Constraints:** * `1 <= q <= p <= 1000`
null
Follow the rules and solve
masking-personal-information
0
1
\n\n# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n # Email\n if \'@\' in s:\n s = s.lower()\n a = s.split(\'@\')[0]\n b = s.split(\'@\')[1]\n a = a[0]+\'*\'*5+a[-1]\n return a+\'@\'+b\n # Phone Number\n else:\n for x in \'+-() \':\n s = s.replace(x, \'\')\n \n ln = len(s)\n res = \'\'\n if ln>10:\n res = \'+\'+\'*\'*(ln-10)+\'-\'\n res+=\'***-***-\'+s[-4:]\n return res\n\n return \'\'\n```
1
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
Follow the rules and solve
masking-personal-information
0
1
\n\n# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n # Email\n if \'@\' in s:\n s = s.lower()\n a = s.split(\'@\')[0]\n b = s.split(\'@\')[1]\n a = a[0]+\'*\'*5+a[-1]\n return a+\'@\'+b\n # Phone Number\n else:\n for x in \'+-() \':\n s = s.replace(x, \'\')\n \n ln = len(s)\n res = \'\'\n if ln>10:\n res = \'+\'+\'*\'*(ln-10)+\'-\'\n res+=\'***-***-\'+s[-4:]\n return res\n\n return \'\'\n```
1
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor. Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_. The test cases are guaranteed so that the ray will meet a receptor eventually. **Example 1:** **Input:** p = 2, q = 1 **Output:** 2 **Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall. **Example 2:** **Input:** p = 3, q = 1 **Output:** 1 **Constraints:** * `1 <= q <= p <= 1000`
null
Python by case solution
masking-personal-information
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)$$ -->\n\n# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n if "@" in s:\n return (s[0]+"*****"+s[s.index("@")-1:]).lower()\n else:\n s=s.replace("(","").replace(")","").replace("-","").replace("+","").replace(" ","")\n if len(s)==10:\n return "***-***-"+s[-4:]\n if len(s)==11:\n return "+*-***-***-"+s[-4:]\n if len(s)==12:\n return "+**-***-***-"+s[-4:]\n if len(s)==13:\n return "+***-***-***-"+s[-4:]\n```
0
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
Python by case solution
masking-personal-information
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)$$ -->\n\n# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n if "@" in s:\n return (s[0]+"*****"+s[s.index("@")-1:]).lower()\n else:\n s=s.replace("(","").replace(")","").replace("-","").replace("+","").replace(" ","")\n if len(s)==10:\n return "***-***-"+s[-4:]\n if len(s)==11:\n return "+*-***-***-"+s[-4:]\n if len(s)==12:\n return "+**-***-***-"+s[-4:]\n if len(s)==13:\n return "+***-***-***-"+s[-4:]\n```
0
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor. Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_. The test cases are guaranteed so that the ray will meet a receptor eventually. **Example 1:** **Input:** p = 2, q = 1 **Output:** 2 **Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall. **Example 2:** **Input:** p = 3, q = 1 **Output:** 1 **Constraints:** * `1 <= q <= p <= 1000`
null
Easy Solution || Helpful for beginners || Clearly Understandable...
masking-personal-information
0
1
# INFORMATION:\n```\nNAME : NARRESH KUMAR S\nSITE : nareshkumar.allgen.tech\n```\n# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n def phNo(s):\n n = ""\n res = ""\n for i in s:\n if i.isdigit():\n n += i\n l = len(n)\n if l==10:\n res += "***-***-"\n for i in range(l-4,l):\n res += n[i]\n return res\n\n elif l==11:\n res += "+*-***-***-"\n for i in range(l-4,l):\n res += n[i]\n return res\n \n elif l == 12:\n res += "+**-***-***-"\n for i in range(l-4,l):\n res += n[i]\n return res\n\n elif l == 13:\n res += "+***-***-***-"\n for i in range(l-4,l):\n res += n[i]\n return res\n res = ""\n if(\'@\' not in s):\n res = phNo(s)\n else:\n s = s.lower()\n res += s[0]\n l = s.index(\'@\')\n res += "*****" + s[l-1]\n res += s[l:len(s)]\n return res\n \n \n \n```
0
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
Easy Solution || Helpful for beginners || Clearly Understandable...
masking-personal-information
0
1
# INFORMATION:\n```\nNAME : NARRESH KUMAR S\nSITE : nareshkumar.allgen.tech\n```\n# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n def phNo(s):\n n = ""\n res = ""\n for i in s:\n if i.isdigit():\n n += i\n l = len(n)\n if l==10:\n res += "***-***-"\n for i in range(l-4,l):\n res += n[i]\n return res\n\n elif l==11:\n res += "+*-***-***-"\n for i in range(l-4,l):\n res += n[i]\n return res\n \n elif l == 12:\n res += "+**-***-***-"\n for i in range(l-4,l):\n res += n[i]\n return res\n\n elif l == 13:\n res += "+***-***-***-"\n for i in range(l-4,l):\n res += n[i]\n return res\n res = ""\n if(\'@\' not in s):\n res = phNo(s)\n else:\n s = s.lower()\n res += s[0]\n l = s.index(\'@\')\n res += "*****" + s[l-1]\n res += s[l:len(s)]\n return res\n \n \n \n```
0
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor. Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_. The test cases are guaranteed so that the ray will meet a receptor eventually. **Example 1:** **Input:** p = 2, q = 1 **Output:** 2 **Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall. **Example 2:** **Input:** p = 3, q = 1 **Output:** 1 **Constraints:** * `1 <= q <= p <= 1000`
null